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.
用两个int分别指向数组的开始和结尾,然后从前往后扫,如果发现有相同的值,则把它移到数组末尾,末尾的指针往前移,否则开始的指针往后移,直到两个指针相遇为止。
需要注意的是数组为空的情况。
int removeElement(int A[], int n, int elem) { // Start typing your C/C++ solution below // DO NOT write int main() function int i = 0, j = n - 1; int t; if(n == 0) return 0; while(i != j){ if(A[i] != elem){ i++; } else{ t = A[i]; A[i] = A[j]; A[j] = t; j--; } } if(A[i] == elem) i--; return i+1; }