給定一個數組和一個值,刪除該值的所有實例,並返回新的長度。
元素的順序可以被改變,也不關心最終的數組長度。
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.
class Solution {
public:
int removeElement(vector& nums, int val) {
if (nums.begin() == nums.end()) return 0;
vector::iterator itor;
for (itor = nums.begin(); itor + 1 != nums.end(); )
{
if (*(itor + 1) == val) {
nums.erase(itor + 1);
}
else {
itor++;
}
}
itor = nums.begin();
if (*itor == val) {
nums.erase(itor);
return nums.size();
}
return nums.size();
}
};