1.Problem description
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.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
中文:数组去重,return新的数组长度。
2.My solution1(Call library functions)
Leetcode上刷的第一道题,跟Topcoder风格类似,需要按照他给的类写函数,不需要给输入输出。
因为适应了STl,直接用Vector库函数写的,后来了解到leetcode上应该尽力实现裸的算法。
Mycode:
</pre><p><pre name="code" class="cpp">class Solution {
public:
int removeElement(vector<int>& nums, int val) {
vector<int>::iterator It;
It = nums.begin();
while(It!=nums.end())
{
if(*It==val)
{
It= nums.erase(It);
continue;
}
It++;
}
return nums.size();
}
};
Tricks:
Vector删除多个元素时需要重新赋值迭代器。
当调用erase()后Iter迭代器就失效了,变成了一野指针。所以要处理这种问题,关键是要解决调用erase()方法后,Iter迭代器变成野指针的问题,这个时候给他赋一个新的迭代器。第一种是重新从头开始迭代,第二种是把删除元素的下一个迭代器给它。
for(Iter = v1.begin(); Iter != v1.end(); Iter++)
{
if(*Iter == 10)
{
v1.erase(Iter);
Iter = v1.begin(); //当erase后,旧的容器会被重新整理成一个新的容器
}
}
还有一种方法是直接赋删除元素的下一个迭代器给Iter
实现方法的代码如下:
for(Iter = v1.begin(); Iter != v1.end(); Iter++)
{
if(*Iter == 10)
{
Iter = v1.erase(Iter);//Iter为删除元素的下一个元素的迭代器
//即第一次这段语句后Iter会是20,大家可以通过debug调试出来查看下数值
}
if(Iter == v1.end()) //要控制迭代器不能超过整个容器
{
break;
}
}
3.My solution2(Two Pointers)
Leetcode上的题目偏重面试题目,标程用的是两个指针,很好实现。
int removeElement(vector<int>& nums, int val) {
int i=0;
int j=0;
int len=nums.size();
for(j;j<len;j++)
{
if(nums[j]!=val)
{
nums[i]=nums[j];
i++;
}
}
return i;
}