80 Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?

For example: Given sorted array nums = [1,1,1,2,2,3], your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

Solution

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int n = nums.size();
        int i  = 0, j = 0;
        while ( i < n ) {
            int k = 0;
            while ( i+k < n and nums[i+k] == nums[i] ) k++;
            nums[j++] = nums[i++];
            if ( k >= 2 ) nums[j++] = nums[i++];
            if ( k >= 3 ) i = i+k-2;
        }
        return j;
    }
};

results matching ""

    No results matching ""