Problem

Given an array and a value, remove all occurrences of that value in place and return the new length.

The order of elements can be changed, and the elements after the new length don't matter.

Example

Given an array [0,4,4,0,0,2,4,4], value=4

return 4 and front four elements of the array is [0,0,0,2]

Note

双指针I:头指针i等于指定元素elem的时候,用尾指针j的值替换i的值(A[i] = A[--j]);否则头指针i继续向后走。
双指针II:i和j都作为头指针,当i的值不是指定元素elem的时候,将A[i]复制到j的位置;否则i继续向后走。最后返回j,就是所有非elem元素的数量。

Solution

1. 双指针I

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

2. 双指针II

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

linspiration
161 声望53 粉丝