pic

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

分析

题意是:继“Remove Duplicates from Sorted Array”,如果允许2个内的重复元素,调整数组,并返回元素个数。

这道题目是“Remove Duplicates from Sorted Array”的扩展,只需要在原来的基础上,在给新位置赋值时,添加一个判断,判断一下重复元素个数是否超过2.

Code

class Solution {
public:
    /* 
     *  设置一个计数器统计重复元素出现的次数,超过2则去除
     *
     * */
    int removeDuplicates(int A[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if( n == 0)     return 0;
        int MostAllowedNum = 1;
        int N = 2;

        int start = 1;
        for(int i = 1; i < n; i++)
        {
            if(A[i] == A[i-1])
            {   
                MostAllowedNum++;
                if(MostAllowedNum > N)
                    continue;
                else
                    A[start++] = A[i];
            }
            else
            {
                A[start++] = A[i];
                MostAllowedNum = 1;
            }
        }
        //for(int i = 0; i <start; i++)
        //  cout<<A[i]<<"  ";
        //cout<<endl;
        return start;
    }
};

pic