Description

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

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 len = nums.size();
        if(len == 0) return 0;
        
        int index = 0, count = 1;
        for(int i = 1; i < len; ++i){
            if(nums[i] != nums[i - 1]){
                count = 1;
                index++;
                nums[index] = nums[i]; //直接覆盖,不要交换,交换会有bug
            }
            else{
                if(count < 2){
                    index++;
                    count++;
                    nums[index] = nums[i];
                }
            }
        }
        
        return index + 1;
    }
};

相关文章:

  • 2022-01-09
  • 2021-12-09
  • 2021-09-23
  • 2021-06-01
  • 2021-10-02
  • 2021-11-17
  • 2021-11-25
猜你喜欢
  • 2021-07-24
  • 2022-03-04
  • 2021-10-04
  • 2021-07-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案