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;
}
};