26. Remove Duplicates from Sorte

2018-01-21  本文已影响0人  i_Eloise

Question:
Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()==0) return 0;
        if(nums.size()==1) return 1;
        int length = 1;
        int first = 0;        
        for(int i = 1 ; i < nums.size();i++)
        {
            if(nums[i]==nums[first])
            {
                continue;
            }
            else
            {
                nums[first+1]= nums[i];
                first++;
                length++;
            }
          }
        return length;
    }
};

易错点:

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

后面的比较是至少有2个元素的,前面就要把vector只有一个元素和没有元素的情况考虑到

上一篇下一篇

猜你喜欢

热点阅读