Sunday, September 15, 2013

Remove Element

Q:
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.

A:
 --------------------3rd pass------------------
不需要像前两次那样,用i,j两个指针。一个slow就够了。然后用for loop来遍历。
public class Solution {
    public int removeElement(int[] A, int elem) {
        if(A==null || A.length ==0) return 0;
        int slow = -1;
        for(int i =0;i<A.length;i++)
            if(A[i]!=elem)
                A[++slow]=A[i];
        return slow+1;
    }
}




-----------1 st pass-------------------
public class Solution {

    public int removeElement(int[] A, int elem) {

        if (A == null) {
            return 0;
        }
        int n = A.length;
        int i = 0;
        int j = n; // j point to the index of element that JUST(moved) equals to
                    // elem
        while (i <= j) {
            // runng forward i ,to the first value of elem
            while (i < j && A[i] != elem) {
                i++;
            }
            // set the value at i as A[j-1] and update j
            if ( i < j && A[i] == elem ) {
                A[i] = A[j - 1];
                j--;
            } else{
                break;
            }
        }
        return j;
    }

}


Mistakes:
 1: 数组的边界检查,总是应该的

 因为总是检查i<j了。 那么在update j 的时候,也需要检查是否越界。
-------------一个好的习惯就是,在用arrayIndex的时候,总是加上  检查越界的判断。

------------------------第二遍--------------------


public class Solution {
    public int removeElement(int[] nums, int val) {
        int endIndex = nums.length-1;
        for(int i =0;i<=endIndex;i++){
            if(nums[i]==val){
                nums[i] = nums[endIndex];
                endIndex--;
                i--;
            }
        }
        return endIndex+1;
    }
} 



Learned:





No comments:

Post a Comment