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();
}
};