leetcode解题报告(8):Remove Element
描述
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 = 3Your function should return length = 2, with the first two elements of nums being 2.
分析
遍历该vector,判断当前元素是否和给定val相等,如果相等,就将该值删除,否则就遍历下一个元素,需要注意的一点是调用erase函数会使迭代器失效。如:
vector<int>vi = {1,2,3,4,5,6};
for(auto i = vi.begin(); i != vi.end(); ++i){
if(*i == 3)
vi.erase(i); //error:iterator i is invalid
}
调用vi.erase(i),会使迭代器i失效,在这种情况下,对迭代器做任何操作都会出错。正确的方法是给定一个返回值,该返回值指向被删除的元素的下一元素:
vector<int>vi = {1,2,3,4,5,6};
for(auto i = vi.begin(); i != vi.end();){
if(*i == 3)
i = vi.erase(i); //error:iterator i is invalid
else
++i;
}
代码如下:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
auto iter = nums.begin();
while(iter != nums.end()){
if(*iter == val)iter = nums.erase(iter);
else ++iter;
}
return nums.size();
}
};
也可以不用erase函数,另一种解法如下:
https://discuss.leetcode.com/topic/20654/a-simple-c-solution
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int index = 0;
for(int i = 0; i != nums.size(); ++i){
if(nums[i] != val){
nums[index] = nums[i];
++index;
}
}
return index;
}
};