27. Remove Element
val = 1 nums = [1,1,2,3] for i in nums: if i == val: nums.remove(i) a = nums result :
val = 1 nums = [1,1,2,3] for i in nums[:]: if i == val: nums.remove(i) a = nums result:
不用remove的解法: class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :rtype: int """ if not nums: return 0 tail = 0 for i in range(len(nums)): if nums[i]!=val: nums[tail]=nums[i] tail+=1 return tail
当 return错误数 的时候,有可能会产生index out of range
时间: 2024-10-01 10:24:35