Simple C++ solution with explanation


  • 0
    U
    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            
            auto numsSize = nums.size();
            
            if(numsSize < 1) return 0; // if vector has 0 elements then return
            
            int counter = 0;
            
            for(int i  = 0; i < numsSize - 1; i++)
                if(nums[i]!= nums[i+1]) nums[counter++] = nums[i];
        
            // since we miss the last element either (1) there was a duplicate like ....5,5 and we iterated over it 
            // or (2) there was a unique element and we only put one of them like 5,6 --> 5 enters and we miss 6
            nums[counter++] = nums[numsSize-1];
            
            return counter;
        }
    };
    

Log in to reply
 

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