Remove Duplicates from Sorted Array II

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

For example,Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

该问题是“去除重复元素,只保留单独一个”的加强版。http://blog.csdn.net/ojshilu/article/details/14123473

思路:仍然使用左右双指针,需要设定一个计数器,记录刚才的元素重复过几次。如果只重复次数到2,就不再存入。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n < 3)
            return n;
        
        int left, right, count;
        left = right = count = 1;
        
        while(right < n)
        {
            if(A[right] == A[right-1])
            {
                if(count < 2)   //第三个重复数
                {
                    A[left++] = A[right++];
                    count++;
                }
                else    //前2个重复数
                {
                    right++;
                }
            }
            else    //第一个出现数
            {
                A[left++] = A[right++];
                count = 1;
            }
        }
        return left;
    }
};


你可能感兴趣的:(Remove Duplicates from Sorted Array II)