Monday, November 25, 2013

LeetCode Problem : Remove Duplicates from Sorted Array II

Problem


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

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 < 3)
        return n;
    int j = 2;
    for(int i = j;i < n; ++i){
        if((A[i] != A[j - 1]) || (A[j - 1] != A[j - 2])){
            A[j] = A[i];
            ++j;
        }
    }
    return j;
}

No comments:

Post a Comment