首页 > 代码库 > 第18题 Remove Element

第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;
    }
}



第18题 Remove Element