Simplest possible c++ code.


  • 0
    S
    class Solution {
      public:
       int removeDuplicates(vector<int>& nums) {
        int i;
        if(nums.size()==0)
            return 0;
        if(nums.size()==1)
            return 1;
            
        for(i=1;i<nums.size();){
            if(nums.at(i)==nums.at(i-1))
                nums.erase(nums.begin()+i);
            else
            i++;
        }
        return i;
       }
    };

  • 0
    A

    Your code can be simplified into this:

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

    Your original solution yielded 64 ms. This can reach 56 ms.
    It removes the redundant checks.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.