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<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变量表明到底出现了几次。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容