1. 概述
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.
本题如上面所说的,你要返回一个数组和一个长度(答案检查中不管这个长度之后的元素),因而只需要使得到的数组在返回回来的长度内没有包含规定的数组就可以了。2. 编码
2.1 方法1
这个方法的思想:从最后一个开始遍历,如果当前数不是规定的数,那么将其弹出并且添加到最前;如果等于规定的数,直接弹出
class Solution {
public:
int removeElement(vector<int>& nums, int val)
{
int len(nums.size());
if(0 == len) return 0;
//方法1 开销大 重新分配
for(int i=0; i<len; i++)
{
int temp_size(nums.size());
if(nums[temp_size-1] == val)
{
nums.pop_back();
}
else
{
int num = nums.back();
nums.pop_back();
nums.insert(nums.begin(), num);
}
}
return static_cast<int>(nums.size());
}
};
性能
2.2 方法2
这个方法的思想:填一个计数数字,从第一个开始遍历,如果当前数不是规定的数,那么将其赋值到计数位置的位置,计数加加;如果等于规定的数,不做操作
class Solution {
public:
int removeElement(vector<int>& nums, int val)
{
int len(nums.size());
if(0 == len) return 0;
//方法1
int count(0);
auto it = nums.begin();
for(int i=0; i<len; i++)
{
if(val != nums[i])
{
nums[count++] = nums[i];
}
}
return count;
}
};
性能
2.3 方法3
这个方法的思想:直接删除删除数组中规定的数字
class Solution {
public:
int removeElement(vector<int>& nums, int val)
{
int len(nums.size());
if(0 == len) return 0;
//方法3
int pos(0);
while(true)
{
auto it = nums.begin();
if(nums[pos] == val)
{
nums.erase(it+pos);
if(0 == nums.size()) break;
pos = 0;
continue;
}
++pos;
if(pos >= nums.size()) break;
}
return static_cast<int>(nums.size());
}
};
性能