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.
cpos是当前可写入位置的前一个位置,遍历A,如果不是elem则递增cpos并写入。
-----------------
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int cpos = -1;
for (int i = 0; i < n; i++) {
if (A[i] != elem) {
A[++cpos] = A[i];
}
}
return cpos + 1;
}
};
本文介绍了一种在数组中移除指定值的所有实例,并返回新数组长度的算法。该算法通过遍历数组并将非目标值元素向前移动来实现,不保留原始顺序。
434

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



