原题:
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.
解法1:
public int removeElement(int[] A, int elem) {
int i = 0;
int j = A.length-1;
while(i<=j) {
while(i<=j && A[i]!=elem) {
i++;
}
while(i<=j && A[j]==elem) {
j--;
}
if(i<=j) {
A[i] = A[j];
i++;
j--;
}
}
return i;
}
另一种写法:
public int removeElement(int[] A, int elem) {
int i = 0;
int j = A.length-1;
while(i<=j) {
if(A[i] == elem) {
A[i] = A[j--];
} else {
i++;
}
}
return i;
}