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.
返回删除元素后的数组长度,使用迭代器操作中的erase来删除元素即可,erase返回删除元素的下一个位置的迭代器。使用erase后元素彻底被删除,所以数组的大小变成删除元素后的数组大小。
class Solution { public: int removeElement(vector<int>& nums, int val) { for (auto iter = nums.begin(); iter != nums.end(); iter++) { if (*iter == val) { iter = nums.erase(iter); iter--; } } return nums.size(); } }; // 6 ms
使用双指针来遍历数组,如果头指针指向的元素和目标值相等,则将尾指针的值赋给头指针元素,然后尾指针向前移动一位,头指针继续判断该位置元素是否和目标值相同。
class Solution { public: int removeElement(vector<int>& nums, int val) { int n = nums.size(); for (int i = 0; i != n; i++) { if (nums[i] == val) { nums[i] = nums[n - 1]; n--; i--; } } return n; } }; // 6 ms