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.
Analysis:
two pointers scan, one variable record the frequency of the value, detailed see in code
Java
public int removeElement(int[] A, int elem) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int count = 0;
for(int i=0;i<A.length;i++){
if(A[i] == elem)
count++;
else if(count>0)
A[i-count] = A[i];
}
return A.length - count;
}
Another one:
public int removeElement(int[] A, int elem) {
int count = 0;
for(int i=0;i<A.length;i++){
if(A[i]!=elem){
A[count++]=A[i];
}else{
continue;
}
}
return count;
}c++
int removeElement(int A[], int n, int elem) {
int cur =0;
for(int i=0;i<n;i++){
if(A[i]==elem)
continue;
A[cur] = A[i];
cur++;
}
return cur;
}

本文介绍了一种通过双指针扫描和变量记录频率的方法,在原地删除数组中指定元素,并返回新数组的长度。提供两种Java实现方式,包括直接覆盖和循环跳过操作。
303

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



