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 int removeElement(int[] A, int elem) {
}
给你一个数组,和一个值,移除所有该值的元素,返回新长度。
数组元素顺序可变,只要返回正确的新长度即可。
public int removeElement(int[] A, int elem) {
if(A.length==0) return 0;
int p=0;
for(int i=0;i<A.length;i++){
if(A[i]!=elem){
A[p++]=A[i];
}
}
return p;
}
本文介绍了一种简单的算法,用于从数组中移除指定值的所有实例,并返回处理后的数组新长度。该算法通过一次遍历实现,保持了较高的效率。
162

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



