2014年11月23日星期日

[Leetcode] 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.
Simple problem. Since you do not need to hold the order of the original array.
    public int removeElement(int[] A, int elem) {
        if(A.length == 0) 
            return 0;
        int p1= 0, p2 = A.length - 1;
        while(p1 <= p2) {
            if(A[p1] == elem) {
                A[p1] = A[p2];
                p2--;
            }
            else
                p1++;
        }
        return p1;
    }

没有评论:

发表评论