1. 程式人生 > >從排序數組中刪除重復項

從排序數組中刪除重復項

個數 fun aid remove 元素 有序數組 else pos tle

給定一個有序數組,你需要原地刪除其中的重復內容,使每個元素只出現一次,並返回新的長度。

不要另外定義一個數組,您必須通過用 O(1) 額外內存原地修改輸入的數組來做到這一點。

個人代碼,較為弱智。

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
  vector<int>::iterator iter;
  int m;
  if(nums.size()==0) return 0;
  else m=nums[0];
  for(iter=++nums.begin();iter!=nums.end();)
  {
    if(*iter!=m){
    m=*iter;
    ++iter;
    }
    else{

    iter=nums.erase(iter);

    }
  }
  return int(nums.size());
  }
};

排名第一代碼:

思路很簡單,就是遍歷數組,不同的元素提前,不會改變數組大小。

class Solution {

public:

int removeDuplicates(vector<int>& nums){

  short int endpos = 0;

  if (nums.size() == 0) return 0;

  for(short int i = 0; i<nums.size(); ++i) {

    if(nums[endpos]!=nums[i]){

      nums[++endpos] = nums[i];

    }

  }

  return endpos +1;

}

};

從排序數組中刪除重復項