题目
Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
思路
这道题也挺好的,虽然难度是easy的,但是挺有意思,题目意思就是给定一个数组,然后给定一个数,把数组中与给定的数相同的元素移除,一看好像挺简单的,我们可以把这个数组遍历一遍,然后把与给定这个数不同的元素复制到另外一个数组就可以了,但是题目中有个要求空间复杂度是,也就是说不能额外创建数组了,这样一来原来这个简单的思路就不行了,那么再来想下别的方法,可以用迭代器遍历这个vector,然后与给定的数进行比较,如果相同,那么我们可以用vector自带的erase()方法删除这个元素就可以了,这样可以解决这个问题,但是时间上可能会慢很多,vector底层实现是用数组实现的,用一个迭代器去删除一个元素不像链表那样简单直接指针指向下下一个元素就好,数组需要移动,要把后面的元素依次向前移动一位,如果数组中没有一个元素与给定的数相同那么时间复杂度是
,如果数组中所有的数都与给定的数相同,那么时间复杂度就是
了,虽然这种方法也能AC。
下面再来说一种思路,用for循环遍历一遍数组实现,从第0位开始,与给定的数进行比较,如果相同那么就把后面的数覆盖掉当前这个数,这样一来时间上能快很多了,那么具体要怎么覆盖呢?首先定义一个变量n,如果数组中元素与给定的数比较不相同那么这个n就加1,然后用这个n和i相加的那位覆盖当前这一位,因为会出现很多个元素和给定的数相同,出现一次后面每遍历一个元素就要把i+1位的数覆盖当前的数,出现两次就要把i+2位的数覆盖当前的数,依次类推,然后再记录数组的长度就可以了。
代码
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int len=nums.size();
if(len==0) return 0;
int lenght=0,n=0;
for(int i=0;i+n<len;){
if(nums[i]==val){
if(i+1+n<len)
nums[i]=nums[i+1+n];
n++;
}
else{
i++;
if(i+n<len)
nums[i]=nums[i+n];
}
}
len-=n;
return len;
}
};