Update 0027.移除元素.md

the former code has not consider if nums is None or len(nums)==0
This commit is contained in:
JaneyLin
2022-06-06 21:49:32 -05:00
committed by GitHub
parent 87abfa1664
commit f49b2e4a75

View File

@ -173,28 +173,24 @@ class Solution {
Python Python
```python ```python3
class Solution: class Solution:
"""双指针法 def removeElement(self, nums: List[int], val: int) -> int:
时间复杂度O(n) if nums is None or len(nums)==0:
空间复杂度O(1) return 0
""" l=0
r=len(nums)-1
@classmethod while l<r:
def removeElement(cls, nums: List[int], val: int) -> int: while(l<r and nums[l]!=val):
fast = slow = 0 l+=1
while(l<r and nums[r]==val):
while fast < len(nums): r-=1
nums[l], nums[r]=nums[r], nums[l]
if nums[fast] != val: print(nums)
nums[slow] = nums[fast] if nums[l]==val:
slow += 1 return l
else:
# 当 fast 指针遇到要删除的元素时停止赋值 return l+1
# slow 指针停止移动, fast 指针继续前进
fast += 1
return slow
``` ```