C++ code, quite standard


  • 5
    D

    You only need to change K to allow K repetitions.
    One common mistake one can make is " if(nums[i] != nums[i-K])" : it is wrong since nums[i-k] can be overwritten in a previous iteration.

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int len=nums.size(), i, K=2, last = K;
            if(len<=K) return len;
            for(i=K; i<len; ++i)
            {
                if(nums[i] != nums[last-K]) nums[last++] = nums[i]; // note it is last-K
            }
            return last;
        }
    };

Log in to reply
 

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