第18题 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.

Solution1:

public class Solution {
    public int removeElement(int[] A, int elem) {
        int length=0, ptr=0;
        for(int i=0; i<A.length;i++){
            if(A[i]!=elem){
                A[ptr]=A[i];
                ptr++;
                length++;
            }
        }
        return length;
    }
}
Solution2:不要的用数组尾的数据填充,改变数组长度就可以

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



posted on 2017-07-25 12:10  yjbjingcha  阅读(136)  评论(0编辑  收藏  举报

导航