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 A = [1,1,1,2,2,3],

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

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n<=1)return n;
        int current=A[0],p1=1,p2=1;
        int th=0;
        for(;p1<n;p1++){
            if(A[p1]==current){
                if(th<1){
                    
                    A[p2]=A[p1];
                    p2++;
                    th++;
                }
                else{
                    
                }
            }
            else{
                th=0;
                current=A[p1];
                A[p2]=A[p1];
                p2++;
            }
        }
        return p2;
    }
};

 

posted @ 2013-08-15 15:09  懒猫欣  阅读(206)  评论(0编辑  收藏  举报