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.
越努力,越幸運