Share my C++ solution,easy to understand


  • 2
    V
    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int n = nums.size();
            if (n < 3)
                return n;
                
            int i = 0, newSize = 2;
            
            for (i = 2; i < n; i++)
            {
            //if the current element is different from the penultimate element of the new nums,add the current element into the new nums 
                if (nums[i] != nums[newSize-2])
                    nums[newSize++] = nums[i];
            }
            
            return newSize;
        }
    };

Log in to reply
 

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