80.Remove Duplicates from Sorted Array II

给定一个数组,里面的元素从小到大排列,将元素整理,使其同一个数最多出现2次,返回整理后的大小。

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.


思路:
题目说每一个数最多出现2次,且数组是有序的,所以直接遍历数组,使用2个变量,conut和idx,count记录同一个数出现的次数,如果大于2次,则跳过,否则将其写到idx记录的下标;idx表示记录答案的下标。对于下标为0的数,他没有可以跟他比的前一个数,所以直接从下标1开始遍历,但因为跳过了一个数,所以初始conut = 1. 后续的数都跟前一个数比较,相等就将count++,不等就将count = 1.

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) return 0;
        int n = nums.size(), count = 1, idx = 1;
        for (int i = 1; i < n; i++) {
            if (nums[i] == nums[i - 1]) count++;
            else count = 1;
            if (count > 2) continue;
            nums[idx++] = nums[i];
        }
        return idx;
    }
};
原文地址:https://www.cnblogs.com/luo-c/p/13030758.html