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.
思路:
先把所有的给定数值都挪到数组末端,然后再用erase删除掉这些元素。
解:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
if(!nums.size())
return 0;
auto itFront = nums.begin();
auto itBack = --nums.end();
for(; itFront < itBack; itFront++)
{
if(*itFront == val)
{
while(*itBack == val && itBack > itFront)
itBack--;
*itFront = *itBack;
*itBack = val;
}
}
for(itFront = nums.begin(); *itFront != val && itFront != nums.end(); itFront++);
if(itFront != nums.end())
nums.erase(itFront, nums.end());
return nums.size();
}
};