您的位置:首页 > 其它

【LeetCode】27. Remove Element

2016-03-08 10:26 162 查看
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<int>& nums, int val) {
if(nums.size() == 0) return 0;
int len = nums.size();
int count = 0;
for(int i =0; i < len; i++)
{
if(nums[i]!=val)
{
nums[count] = nums[i];
count++;
}
}
return count;
}
};


二刷:先将vector排序,用迭代器遍历,当出现指定元素时就删除。

Runtime: 4
ms

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int len = nums.size();
if(len==0) return 0;
sort(nums.begin(),nums.end());
int count = 0;
for(vector<int>::iterator it= nums.begin(); it != nums.end(); it++)
{
if((*it)==val)
{
nums.erase(it);
it--;
count++;
}
}
return len - count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: