Labels

Friday, February 13, 2015

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.

Naive Way:最典型的array manipulate题目,我觉得这种题的关键就是 “无效数字的位置可以被有效数字所覆盖,一慢一快两个指针”。

public class Solution {
    public int removeElement(int[] A, int elem) {
        int i = 0, j = -1;
        while(++j < A.length) if(A[j]!=elem) A[i++] = A[j];
        return i;
    }
}

 

No comments:

Post a Comment