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

Have you been asked this question in an interview?
The solution is just use a pointer to keep track of the last element of the finished array, notice this pointer should start from -1.

public class Solution {
    public int removeDuplicates(int[] A) {
        if (A.length == 0)
            return 0;
        int p = -1; // pointer to hold the last element of the finished array
        for (int i = 0; i < A.length; i++) {
            if ( p-1 >= 0 && A[p] == A[i] && A[p-1] == A[i])
                continue;
            else
                p++;
                A[p] = A[i];
        }
        return p + 1;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s