27. Remove Element
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 1:
1 | Given input array nums = [3,2,2,3], val = 3 |
思路:需要从列表中删除指定val的元素,需要返回新列表的长度,另外看到提示中不管元素原来的顺序,很自然的想到会是从首尾同时开始找,找到了就开始swap,最后新列表前面的子列表就是需要的新列表,首指针的值就是新列表的长度
1 | class Solution: |
另外python版本还有一个更简单的方法
1 | while val in nums: |