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.
分析:方法很简单,使用两个游标i,j,
遍历数组,如果碰到了value,使用j记录位置,同时递增i,直到下一个非value出现,
将此时i对应的值复制到j的位置上,
增加j,重复上述过程直到遍历结束。这时候j就是新的数组长度。
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int i = 0;
int j = 0;
for(i = 0; i < n; i++) {
if(A[i] == elem) {
continue;
}
A[j] = A[i];
j++;
}
return j;
}
};
本文介绍了一种简单高效的算法,用于在数组中删除指定值的所有实例,并返回新数组的长度。通过使用双游标i和j遍历数组,当遇到目标值时跳过,否则将非目标值复制到当前位置并更新j。最终j指示了新数组的有效长度。
1420

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



