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