1 python list可以使用索引的特性,从后往前遍历。
2 按照list的常规做法,从开头每次验证下一个节点是否与val相同,
最后验证头结点。
3使用python list.remove()函数,删除所有的val。
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
# method 1
end = len(nums)-1
while end > -1:
if nums[end] == val:
del nums[end]
end = end - 1
return len(nums)
# method 2
if len(nums) == 0:
return 0
start = 0
while 1:
#print(start,nums)
if start == (len(nums)-1) or len(nums) == 0:
break
if nums[start+1] == val:
del nums[start+1]
else:
start = start + 1
if nums[0] == val:
del nums[0]
return len(nums)
# method 3
#nums = [3,3]
flag = True
while flag:
if val in nums:
nums.remove(val)
else:
flag = False
return len(nums)
第一种最快,64ms,O(n)
第二种第三种差不多,70ms左右。第二种判断条件多,
第三种remove每次删去的是第一个val值,所以相当于每次删除
把数组遍历了一遍。0(kn)k是val的个数。