Thursday, May 29, 2014

Remove Duplicates from Sorted Array II

This is my first version of code for this problem. The code below should be easy to understand. Actually, I think some variables are redundant. If these variables are removed, code gets improved, then we can finish this problem in-place. I will update the improvement sooner or later.

public class Solution {
public int removeDuplicates(int[] A) {
     
       int ALen = A.length;
       if (A == null || ALen == 0) return 0;
       if (ALen < 3) return ALen;
       int i = 1;
       int count = 1;
       int num = A[0];
       int currentNum;
       ArrayList<Integer> arrA = new ArrayList<Integer>();
       arrA.add(num);
       while(i < ALen){
           currentNum = A[i];
           if(num == currentNum && count < 2 ){
               count++;
               arrA.add(currentNum);
           }
           else{
               if(num != currentNum){
                   num = currentNum;
                   count = 1;
                   // length ++;
                   arrA.add(num);
               }//  The else case must be "count = 2", no need to deal with it, just move index to next
           }
           i ++;
       }
       i = 0;
       while(i<ALen){
        if(i < arrA.size()){
        A[i] = arrA.get(i);
        }
           i ++;
       }
       return arrA.size();
   }
}

No comments:

Post a Comment