Wednesday, August 20, 2014

Remove Element

Quite easy one. The tricky part may be how to remove element instances so that the whole algorithm takes O(n) time, while in-place. One hint given to us is very helpful: "The order of elements can be changed". So I think that just replace the element we need to remove with a different one, which can be found from end of array. And algorithm stops until start index, or can be also called insert index, meets end index. All elements are traversed just once, so time should be O(n)


 public class Solution {  
   public int removeElement(int[] A, int elem) {  
     if(A.length == 0) return A.length;  
     int startIdx = 0, endIdx = A.length - 1, newLen = A.length;  
     while(startIdx <= endIdx){  
       while(endIdx >= 0 && endIdx!= startIdx && A[endIdx]==elem) {  
         endIdx --;  
         newLen --;  
       }  
       if(endIdx < 0){  
         return newLen;  
       }  
       if(A[startIdx] == elem){  
         A[startIdx] = A[endIdx];  
         endIdx --;  
         newLen --;  
       }  
       startIdx ++;  
     }  
     return newLen;  
   }  
 }  

No comments:

Post a Comment