赞
踩
题目考点
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.
解题思路
代码
- def removeElement(self, nums: List[int], val: int) -> int:
- l = 0
- for i in range(len(nums)):
- if nums[i] != val:
- nums[i],nums[l],l = nums[l],nums[i],l+1
- return l
判断语句处可从swap改为replace,增加效率
- if nums[i] != val:
- nums[l] = nums[i]
- l += 1
加一句判空,如果题目不要求返回任何值,直接写return
- if not nums:
- return 0
总结
题目考点
解题思路
代码
- def removeDuplicates(self, A):
- if not A:
- return 0
- l = 0
- for i in range(1, len(A)):
- if A[i] != A[l]:
- A[l+1] = A[i]
- l += 1
- return l + 1
循环从1开始是因为要从第一项跟l,即有效数组的最后一项比较,相当于check i - 1项
总结
题目考点
解题思路
代码
解法1
- def removeDuplicates(self, nums: List[int]) -> int:
- if len(nums) < 3:
- return len(nums)
- l = 0
- count = 0
- for cur in range(1, len(nums)):
- if nums[cur] != nums[l] :
- count = 0
- nums[l + 1] = nums[cur]
- l += 1
- else:
- count += 1
- if count < 2:
- nums[l + 1] = nums[cur]
- l += 1
- return l + 1
- def removeDuplicates(self, nums: List[int]) -> int:
- if len(nums) <= 2:
- return len(nums)
- l = 0
- count = 0
- for i in range(1,len(nums)):
- if nums[l] != nums[i] :
- count = 0
- if nums[l] == nums[i] :
- count += 1
- if (nums[l] != nums[i]) or (nums[l] == nums[i] and count == 1):
- nums[l + 1] = nums[i]
- l += 1
- return l + 1
解法2
- def removeDuplicates(self, nums: List[int]) -> int:
- i = 0
- for n in nums:
- if i < 2 or n > nums[i-2]:
- nums[i] = n
- i += 1
- return i
总结
题目考点
解题思路
代码
解法1 O(n) + O(k) 整块swap
- def rotate(self, nums: List[int], k: int) -> None:
- l = len(nums)
- k = k % l
- temp = nums[l - k : l] #extra
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。