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 = <code>[3,2,2,3]</code>, val = <code>3</code>
Your function should return length = 2, with the first two elements of nums being 2.
Hint:
Try two pointers.
Did you use the property of "the order of elements can be changed"?
What happens when the elements to remove are rare?
思路:比较容易想到的是初始化新长度pos为0,每当遍历到的元素不为val值,则将他放在pos位置,pos++。比如这个例子pos = 0, i = 0 开始,由于nums[i] == val,所以不操作,nums[1] != val,所以nums[pos](pos = 0) = nums[1],pos++; nums[2] != val,所以nums[pos] = nums[2](pos = 1),pos++;nums[3] == val,不进行赋值操作。最终pos = 2;
在C++ vector中有erase()这个函数,所以每当nums[i] == val,就可以将其删除。
注意到题目所说"the order of elements can be changed",(我没想到这样做。。。学习了别人的代码,如下):思想就是从下标0开始,如果nums[i] == val,则将nums[i]
和数组最后一个元素交换,同时数组长度减1,相当于把这个数排除了。否则比较nums[i+1]和val.
越努力,越幸运