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 f49b2e4

Browse files
Update 0027.移除元素.md
the former code has not consider if nums is None or len(nums)==0
1 parent 87abfa1 commit f49b2e4

File tree

1 file changed

+17
-21
lines changed

1 file changed

+17
-21
lines changed

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

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -173,28 +173,24 @@ class Solution {
173173

174174
Python:
175175

176-
```python
176+
```python3
177177
class Solution:
178-
"""双指针法
179-
时间复杂度:O(n)
180-
空间复杂度:O(1)
181-
"""
182-
183-
@classmethod
184-
def removeElement(cls, nums: List[int], val: int) -> int:
185-
fast = slow = 0
186-
187-
while fast < len(nums):
188-
189-
if nums[fast] != val:
190-
nums[slow] = nums[fast]
191-
slow += 1
192-
193-
# 当 fast 指针遇到要删除的元素时停止赋值
194-
# slow 指针停止移动, fast 指针继续前进
195-
fast += 1
196-
197-
return slow
178+
def removeElement(self, nums: List[int], val: int) -> int:
179+
if nums is None or len(nums)==0:
180+
return 0
181+
l=0
182+
r=len(nums)-1
183+
while l<r:
184+
while(l<r and nums[l]!=val):
185+
l+=1
186+
while(l<r and nums[r]==val):
187+
r-=1
188+
nums[l], nums[r]=nums[r], nums[l]
189+
print(nums)
190+
if nums[l]==val:
191+
return l
192+
else:
193+
return l+1
198194
```
199195

200196

0 commit comments

Comments
(0)

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