LeetCode 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.

class Solution {
public:
    int removeDuplicates(vector& nums) {
        int n = nums.size(), skip = 0;
        if(n <= 2) return n;
        int cnt = 0, index = 0;
        for(int i = 0; i 0 && nums[i] == nums[i-1]){
                cnt++;
                if(cnt >= 3)
                    continue;
            }
            else cnt = 1;
            nums[index++] = nums[i];
        }
        return index;
    }
};

用了index指明了结果数组中每个地方的正确数字,不必每次遇到重复数字时全局移动几乎整个后面的数组,用cnt变量表明到底出现了几次。

你可能感兴趣的:(LeetCode Remove Duplicates from Sorted Array II)