Leetcode–Remove Duplicates from Sorted Array II

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

Notes:

  1. Same as Remove Duplicates from Sorted Array, just add one variable to record number of duplicates.

Java Solution:

public class Solution {
    public int removeDuplicates(int[] A) {
        if(A.length<=1)return A.length;
        int replace = 1;
        int dup = 0;
        int prev = A[0];
        for(int i = 1; i < A.length; i++){
            if(A[i]==prev){
                dup++;
                if(dup<2){
                    A[replace] = A[i];
                    replace++;
                }
            }
            else{
                dup=0;
                prev = A[i];
                A[replace] = A[i];
                replace++;
            }
        }
        return replace;
    }
}
Advertisements

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