您的位置:首页 > 编程语言 > Go语言

LeetCode Algorithms #27 <Remove Element>

2016-04-01 18:39 441 查看
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();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: