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.
2.解题思路
这个其实和标准库STL里面unique算法思想一直,找到第一个相同的元素,然后记住其位置,找到不同的元素,然后和这个位置的交换,然后定位的位置前进一位,直到最后然后进行vector的erase操作。
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.
2.解题思路
这个其实和标准库STL里面unique算法思想一直,找到第一个相同的元素,然后记住其位置,找到不同的元素,然后和这个位置的交换,然后定位的位置前进一位,直到最后然后进行vector的erase操作。
3.代码实现
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
auto rplacPos = nums.end();
auto it = nums.begin();
while (it != nums.end()) {
if (*it == val){
if (rplacPos == nums.end())
rplacPos = it;
}
else if(rplacPos != nums.end()) {
int tmp = *rplacPos;
*rplacPos = *it;
*it = tmp;
++rplacPos;
}
++it;
}
nums.erase(rplacPos, nums.end());
return nums.size();
}
};
4.实现结果