mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
优化 0027.移除元素.md Python3解法
This commit is contained in:
@ -144,15 +144,28 @@ class Solution {
|
|||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
```python
|
```python3
|
||||||
class Solution:
|
class Solution:
|
||||||
def removeElement(self, nums: List[int], val: int) -> int:
|
"""双指针法
|
||||||
i,n = 0,len(nums)
|
时间复杂度:O(n)
|
||||||
for j in range(n):
|
空间复杂度:O(1)
|
||||||
if nums[j] != val:
|
"""
|
||||||
nums[i] = nums[j]
|
|
||||||
i += 1
|
@classmethod
|
||||||
return i
|
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
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user