1.题目
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
删除数组中值等于val的元素并返回数组的长度。
2.思路
这道题很简单,主要是考察earse的用法。erase删除节点指针后,指针后移指向下一个节点。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
for(auto it = nums.begin();it!=nums.end();){
if(*it == val)
nums.erase(it); // 在删除it节点后,it自动指向下一个节点
else
it++;
}
return nums.size();
}
};
本文介绍了一个使用C++实现的算法,用于从数组中删除所有等于特定值的元素,并返回修改后的数组长度。该算法利用了erase函数进行原地操作,避免了额外内存的分配。

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



