Saturday, March 2, 2013

Remove Element

/*
Remove Element
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
*/
class Solution {
public:
    void swap(int A[], int i, int j){
      int temp = A[i];
      A[i] = A[j];
      A[j] = temp;
    }
    int removeElement(int A[], int n, int elem) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int i = 0;
        int j = n-1;
        for(i=0; i<n && i<j; i++){
          if(A[i]==elem){
            while(A[j]==elem && j>=0 && i<=j) j--;
            if(j>=0 && i<=j){
            swap(A,i,j);
            j--;
            } else return i;
          }
        }
       
        if(i==j){
         if(A[i]==elem) return i;
         else return i+1;
        }
       
        if(j==-1) return 0;
       
        if(i==n) return n;
    }
};

No comments:

Post a Comment