Remove Element
My SubmissionsGiven 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.
思路:利用依次覆盖的方法进行处理。
class Solution {
public:
int removeElement(int A[], int n, int elem) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (n < 1)
return 0;
int k = 0;
for (int i = 0; i < n; ++i) {
if (A[i] != elem ) {
swap (A[i - k], A[i]);
}
else {
++k;
}
}
return n - k;
}
};
本文介绍了一种通过依次覆盖的方法来删除数组中指定元素的算法,并返回新数组的长度。该方法简洁高效,适用于各种数组处理场景。
656

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



