[LeetCode]100. 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 1122 and 3. It doesn't matter what you leave beyond the new length.

Subscribe to see which companies asked this question

 
解法:同排序数组去重I,本题的一个额外要求是元素最多可以重复两次。因此需要增加一个计数值,记录当前数字出现次数,计数值cnt初始化为1。同时设置一个索引idx初始化为1,记录下一个保留元素应该保存的位置。从数组的第二个元素开始扫描。如果当前元素和前一个元素相同,则++cnt,此时如果cnt>2了,则跳过这个重复值;如果小于2,则nums[idx++]=nums[i];如果当前元素和前一个元素不相同,则重置cnt=1,且保留下当前元素nums[idx++]=nums[i]。
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() < 3) return nums.size();
        int idx = 1, cnt = 1;
        for (int i = 1; i < nums.size(); ++i) {
            if (nums[i - 1] == nums[i]) {
                ++cnt;
                if (cnt <= 2) nums[idx++] = nums[i];
            }
            else {
                nums[idx++] = nums[i];
                cnt = 1;
            }
        }
        return idx;
    }
};
原文地址:https://www.cnblogs.com/aprilcheny/p/5030671.html