Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d1e9630

Browse files
committed
优化 0027.移除元素.md Python3解法
1 parent 5a467c2 commit d1e9630

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

‎problems/0027.移除元素.md‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -144,15 +144,28 @@ class Solution {
144144

145145
Python:
146146

147-
```python
147+
```python3
148148
class Solution:
149-
def removeElement(self, nums: List[int], val: int) -> int:
150-
i,n = 0,len(nums)
151-
for j in range(n):
152-
if nums[j] != val:
153-
nums[i] = nums[j]
154-
i += 1
155-
return i
149+
"""双指针法
150+
时间复杂度:O(n)
151+
空间复杂度:O(1)
152+
"""
153+
154+
@classmethod
155+
def removeElement(cls, nums: List[int], val: int) -> int:
156+
fast = slow = 0
157+
158+
while fast < len(nums):
159+
160+
if nums[fast] != val:
161+
nums[slow] = nums[fast]
162+
slow += 1
163+
164+
# 当 fast 指针遇到要删除的元素时停止赋值
165+
# slow 指针停止移动, fast 指针继续前进
166+
fast += 1
167+
168+
return slow
156169
```
157170

158171

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /