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()<1)
return 0;
if(nums.size()==1&&nums[0]==val)
return 0;
while(nums[nums.size()-1]==val)
{
nums.pop_back();
}
vector<int>::iterator iter;
for(iter=nums.begin();iter!=nums.end();)
{
if(*iter==val)
iter=nums.erase(iter);
else
iter++;
}
return nums.size();
}
};
本文介绍了一个算法,用于在数组中删除所有指定值的实例,并直接在原数组上进行修改,返回修改后的数组长度。通过迭代和条件判断,实现了一种在不使用额外空间的情况下优化效率的方法。
1400

被折叠的 条评论
为什么被折叠?



