2014年1月14日星期二

LeetCoder - 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.

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

没有评论:

发表评论