Remove Element
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(vector<int>& nums, int val) {
int i = 0, j = nums.size() - 1;
while (i <= j) {
if (nums[i] == val) {
nums[i] = nums[j--];
}
else {
i++;
}
}
return i;
}
};
本文介绍了一种移除数组中特定值的有效算法。通过双指针技术,可以在原地修改数组的同时保持元素顺序不变,最终返回新的有效长度。此方法简单高效,适用于多种编程挑战。
624

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



