题目:
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.
Java AC代码:
public class Solution {
public int removeElement(int[] A, int elem) {
if (A == null || A.length == 0) {
return 0;
}
int p1 = 0, p2 = A.length - 1;
while (p1 < p2) {
while (A[p2] == elem && p1 < p2) {
p2--;
}
while (A[p1] != elem && p1 < p2) {
p1++;
}
if (p1 < p2) {
int temp = A[p2];
A[p2] = A[p1];
A[p1] = temp;
}
}
return A[p1] == elem ? p1 : p1 + 1;
}
}