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

 

Code:

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n<3) return n;
        int i=0;
        bool detect=false;
        for(int j=1;j<n;j++){
            if(A[j]!=A[i]||detect==false){
                if(A[j]!=A[i])
                    detect=false;
                else
                    detect=true;
                A[++i]=A[j];
            }
        }
        return i+1;
    }
};

 

posted @ 2013-11-17 18:52  WinsCoder  阅读(137)  评论(0编辑  收藏  举报