26. Remove Duplicates from Sorted Array

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.

  • second attempt
class Solution {
public:
    int removeDuplicates(vector& 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只有一个元素和没有元素的情况考虑到

你可能感兴趣的:(26. Remove Duplicates from Sorted Array)