Leetcode: 80. Remove Duplicates from Sorted Array II

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;
    }
};
posted @ 2017-06-01 23:07  JeffNice  阅读(112)  评论(0)    收藏  举报