Friday, October 10, 2014

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


    int removeDuplicates(int A[], int n) {
        if (n <= 2)
            return n;
        int j = 1;
        int count = 1;
        for(int i=1; i<n; i++)
        {
            //copy to the dest if current element is equal to previous element and count <= 2
            if (A[i] == A[i-1] && count < 2)
            {
                A[j++] = A[i];
                count++;
            }
            //or current element is not equal to previous element 
            else if (A[i] != A[i-1])
            {
                A[j++] = A[i];
                count = 1;
            }
        }
        
        return j;
    }

No comments:

Post a Comment