美文网首页
LeetCode Remove Duplicates from

LeetCode Remove Duplicates from

作者: codingcyx | 来源:发表于2018-03-27 22:15 被阅读0次
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<int>& nums) {
        int n = nums.size(), skip = 0;
        if(n <= 2) return n;
        int cnt = 0, index = 0;
        for(int i = 0; i<n; i++){
            if(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

      本文链接:https://www.haomeiwen.com/subject/ailecftx.html