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 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:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
代码:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
nums.erase(remove(nums.begin(),nums.end(),val),nums.end());
return nums.size();
}
};
remove只是将所有不等与val的元素向前覆盖,并未删除,所以需要调用erase函数删除。
3 2 2 3第一次遍历后知道不为3的元素为2 2,向前覆盖后得到2 2 2 3,原序列中后面两位在内存中不会移动,remove返回非val的最后一个数后面一位的迭代器,因此要配合erase函数使用。