Movatterモバイル変換


[0]ホーム

URL:


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

Commit41dfdb7

Browse files
authored
Merge pull requestneetcode-gh#3198 from doublewhy/patch-2
Update 0027-remove-element.py
2 parents14daefb +02c2b65 commit41dfdb7

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

‎python/0027-remove-element.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,20 @@ def removeElement(self, nums: List[int], val: int) -> int:
66
nums[k]=nums[i]
77
k+=1
88
returnk
9+
10+
# Optimized solution with the same time and space complexity
11+
classSolution:
12+
defremoveElement(self,nums:List[int],val:int)->int:
13+
# Avoid unessary copy operations in a previous solution, when k == i and nums[i] != val
14+
# by swapping nums[i] and the last element of the array (nums[n])
15+
n=len(nums)
16+
i=0
17+
18+
whilei<n:
19+
ifnums[i]==val:
20+
nums[i],nums[n-1]=nums[n-1],nums[i]
21+
n-=1# decrement the length of the array by discarding the last element
22+
else:
23+
i+=1
24+
25+
returnn

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp