Remove Duplicates from Sorted Array II

LeetCode #80


Description:

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

Example:

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.

Idea:

加一个count variable记录可以重复多少次。

if(nums[i] != nums[index]) {
    nums[++index]=nums[i];
    count = 0;
}
else{
    if(count==0){
        nums[++index]=nums[i];
        count++;
    }
    else
        count++;
}

Code:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size() <= 2) return nums.size();

        int index=0;
        int count=0;

        for(int i=1; i<nums.size(); ++i){
            if(nums[i] != nums[index]) {
                nums[++index]=nums[i];
                count = 0;
            }
            else{
                if(count==0){
                    nums[++index]=nums[i];
                    count++;
                }
                else
                    count++;
            }
        }

        return index + 1;

    }
};

results matching ""

    No results matching ""