[LeetCode]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.

两个指针指,遇到超出范围的情况前指针对数据进行赋值。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int ret = 1;
        int p1 = 0;
        int p2 = 0;
        int count = 1;
        if(nums.size()<2)
            return nums.size();
        nums.push_back(INT_MAX);
        for(p2=1; p2<nums.size(); ++p2){
            if(nums[p2]==nums[p2-1]){
                count++;
            }
            else{
                int add = 1;
                if(count>=2) add = 2;
                ret += add;
                count=1;
                for(int i=p1; i<p1+add; ++i)
                    nums[i] = nums[p2-1];
                p1 += add;
            }
        }
        return ret-1;
    }
};


你可能感兴趣的:(LeetCode)