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 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:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
思路:
本来是准备依次遍历列表,然后遇到 val 就 remove 掉,每一次 remove 只能移除1个数,不过直接用for遍历整个数组进行remove 操作,当列表中的 val 都被移除以后循环还没结束就会报错(列表中没有val, remove函数就会报错列表中没有要移除的数),所以用 count 先数一下 nums 列表中有几个 val,然后循环 count 次,依次remove掉就可以了,比直接遍历列表效率要高。
我的代码:
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
for i in range(nums.count(val)):
nums.remove(val)
return len(nums)