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 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.
也就是给定一个value,要求删除给定数组中所对应的数字,并返回最后的长度。
要求不可以使用新的内存来做,也就是空间复杂度是O(1)。
2,题目思路
因为题目要求的返回值只是最后数组的长度,因此想取巧进行操作:直接统计长度。但是不行,题目的判定方法貌似是根据你所得到的返回值res直接取数组的前res,看是否与删除后的结果相同。
由于题目不允许开辟新的内存,所以删除操作只能在原先的数组上进行完场。有一个惯性思维,即一想到删除就想到pop、remove】delete等操作,但是该情景下并不需要真的将元素从所在内存中抹除。只需要对前res个元素赋值为不用删除的元素即可,后面的元素可以不用去考虑了。本质上是一种排序。
3,程序源码
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int res = 0;
for(int i=0;i<nums.size();i++)
{
if(nums[i]!=val)
{
nums[res] = nums[i];
res++;
}
}
return res;
}
};