Question:
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.
代码如下:
public static int removeElement(int[] A, int elem) {
int length = A.length;
// if (length == 0) {
// return -1;
// }
int newLength = 0;
for (int i = 0; i < length; i++) {
int num = A[i];
if (num != elem) {
A[newLength++] = A[i];
}
}
return newLength;
}
注释:若在leetcode OJ上加上注释的代码,编译通不过。