美文网首页
26. Remove Duplicates from Sorte

26. Remove Duplicates from Sorte

作者: i_Eloise | 来源:发表于2018-01-21 10:58 被阅读0次

    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<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只有一个元素和没有元素的情况考虑到

    相关文章

      网友评论

          本文标题:26. Remove Duplicates from Sorte

          本文链接:https://www.haomeiwen.com/subject/esefaxtx.html