Remove Element
Total Accepted: 89646 Total Submissions: 276815 Difficulty: Easy
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.
思路:1).注意一点nums.erase(it)后,会自动递增it,使得it指向vector的下一个值,此时,如果是for循环中写了it++,就会跳过这个值。因此,it++要写在函数体内。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int size = nums.size();
for(vector<int>::iterator it = nums.begin();it!=nums.end();){
if(*it==val){
nums.erase(it);
size--;
}else{
it++;
}
}
return size;
}
};