题目
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 题目要求是in place
2 直接想到了头尾分割的方法。把所有碰到的元素都放到尾巴,然后获得新的length即可。
public class Solution {
public int removeElement(int[] A, int elem) {
if(A.length==0){
return 0;
}
int cur =0;
int end = A.length-1;
while(cur<=end){
if(A[cur]!=elem){
cur++;
}
else{
int temp =A[cur];
A[cur]=A[end];
A[end]=temp;
end--;
}
}
return cur;
}
}