题目链接:Remove Element
1. Description
-
Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.
-
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,
-
Your function should return length = 2, with the first two elements of nums being 2.
-
It doesn’t matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn’t matter what values are set beyond the returned length.
2. 方法1
因为这里是删除元素的问题,所以我们就搜索vector有没有删除元素的函数,还真有, erase和remove,所以我们写出了第一种代码。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
nums.erase(remove(nums.begin(), nums.end(), val), nums.end());
return nums.size();
}
};
速度相当快,超过100%

注意:
- 这里的remove函数不是真的删除vector元素,和erase是不同的,直观理解remove返回是一个迭代器,然后的话它把需要删除的元素放到最后,然后返回的是最后一个和需要删除元素不等的元素。然后我们结合erase函数可以达到删除元素的效果~
- remove用法直接就是std::remove而不是使用这里的nums.remove,注意和nums.erase用法的区别。
- 这里的话删除的剩下的元素是不需要去重的。
参考文章:
3. 方法2
在题目的solution下面看到了distance,然后我们改进一下我们的代码。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
return distance(nums.begin(),
remove(nums.begin(), nums.end(), val));;
}
};
结果都差不多~

参考文献:
好吧,好的函数的会事半功倍啊,代码也很简洁~
本文介绍如何使用C++ STL中的remove和distance函数高效地从数组中移除特定值,通过具体示例展示了两种实用的方法,并对比了其性能表现。

3987

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



