问题描述:
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.
思路:
由于题目并没有限制最后的 array 的尾部有否其他元素,所以可以很容易想到调换 val 值的元素到末尾即可,这是下面代码二实现的。
一开始查阅了 vector 的函数,想到用 erase 函数,于是一个简单版本方案就是直接删除即可,代码一实现。
代码:
//code I
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int newLength = nums.size();
int temp;
for(vector<int>::iterator it = nums.begin(); it != nums.end(); it++ )
{
if(*it == val)
{
nums.erase(it); //simle and direct
it--;
newLength--;
}
}
return newLength;
}
};
//code II
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int newLength = nums.size();
int temp;
vector<int>::iterator rit = nums.end();
rit--;
for(vector<int>::iterator it = nums.begin(); it != nums.end(); it++ )
{
if(*it == val)
{
temp = *rit;
*rit = val;
*it = temp;
it--;
newLength--;
rit--;
}
if(it == rit)
break;
}
return newLength;
}
};
“`