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.
Solution1:
public class Solution {
public int removeElement(int[] A, int elem) {
int length=0, ptr=0;
for(int i=0; i<A.length;i++){
if(A[i]!=elem){
A[ptr]=A[i];
ptr++;
length++;
}
}
return length;
}
}Solution2:不要的用数组尾的数据填充,改变数组长度即可。
public class Solution {
public int removeElement(int[] A, int elem) {
int length=A.length;
for(int i=0; i<length;i++){
if(A[i]==elem){
A[i]=A[length-1];
length--;
i--;
}
}
return length;
}
}

本文介绍了一种在数组中移除特定值并返回新长度的算法实现,提供了两种不同的解决方案,一种是通过指针向前遍历,另一种是利用数组尾部元素进行填充。

106

被折叠的 条评论
为什么被折叠?



