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.
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int currentIndex = 0;
for (int i=0;i<n;i++){
if (A[i]!=elem){
A[currentIndex] = A[i];
currentIndex++;
}
}
return currentIndex;
}
};
本文介绍了一种在数组中移除指定值并返回新长度的算法实现。该方法通过遍历数组,将不等于目标值的元素向前移动,并最终返回不包含目标值的子数组的有效长度。
435

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



