題目
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.
解題思路:
用兩個(gè)指針,一個(gè)指向結(jié)果數(shù)組,一個(gè)遍歷數(shù)組。
代碼:
public int removeElement(int[] A, int elem) {
if (A.length == 0 || A == null)
return 0;
int i = 0;
int j = 0;
while (j < A.length) {
if (A[j] == elem)
j++;
else
A[i++] = A[j++];
}
return i;
}