Thursday, October 9, 2014

Remove duplicates in sorted array II -- Leetcode

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].
Answer:
public class Solution {
    public int removeDuplicates(int[] A) {
        boolean flag=false;
        int count=0;
        for(int i=1;i<A.length;++i){
            if(A[i]==A[i-1] && flag==false){
                flag = true;                       //second same elem.
                A[i-count] = A[i];
            }
            else if(A[i]==A[i-1] && flag==true){
                count++;                        //elem. needed to be deleted.
            }
            else if(A[i]!=A[i-1]){
                flag = false;                  //flag initia to false for a new different elem.
                A[i-count] = A[i];
            }
        }
        return A.length - count;
    }
}

No comments:

Post a Comment