您的位置:首页 > 其它

Remove Element

2015-08-26 10:46 429 查看
Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

思路:这道题难度不大,但是有个易错点,就是在使用迭代器遍历vector时,找到指定的位置后不能直接删除当前位置的it(vector::iterator it = nums.begin()),如果直接删了就无法链接到这个it之后的元素.代码如下”

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
if(nums.empty())
return 0;
for(vector<int>::iterator it = nums.begin(); it != nums.end();){
if(*it == val){
it = nums.erase(it);//不能写成nums.erase(it);
}
else
it++;
}
return nums.size();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: