mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #2 from janeyziqinglin/janeyziqinglin-patch-2
Update 0027.移除元素.md
This commit is contained in:
@ -183,28 +183,24 @@ class Solution {
|
||||
|
||||
Python:
|
||||
|
||||
```python
|
||||
```python3
|
||||
class Solution:
|
||||
"""双指针法
|
||||
时间复杂度:O(n)
|
||||
空间复杂度:O(1)
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def removeElement(cls, nums: List[int], val: int) -> int:
|
||||
fast = slow = 0
|
||||
|
||||
while fast < len(nums):
|
||||
|
||||
if nums[fast] != val:
|
||||
nums[slow] = nums[fast]
|
||||
slow += 1
|
||||
|
||||
# 当 fast 指针遇到要删除的元素时停止赋值
|
||||
# slow 指针停止移动, fast 指针继续前进
|
||||
fast += 1
|
||||
|
||||
return slow
|
||||
def removeElement(self, nums: List[int], val: int) -> int:
|
||||
if nums is None or len(nums)==0:
|
||||
return 0
|
||||
l=0
|
||||
r=len(nums)-1
|
||||
while l<r:
|
||||
while(l<r and nums[l]!=val):
|
||||
l+=1
|
||||
while(l<r and nums[r]==val):
|
||||
r-=1
|
||||
nums[l], nums[r]=nums[r], nums[l]
|
||||
print(nums)
|
||||
if nums[l]==val:
|
||||
return l
|
||||
else:
|
||||
return l+1
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user