[LeetCode]027. 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.

Solution: use two pointers.

Running Time: O(n).

public class Solution {
    public int removeElement(int[] A, int elem) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int len = A.length;;
        int cur = 0;
        for(int i=0; i<len; i++){
            if(A[i] == elem){
                continue;
            }else{
                A[cur] = A[i];
                cur++;
            }
        }
        return cur;
    }
}



你可能感兴趣的:(LeetCode)