Skip to content

Commit 41dfdb7

Browse files
authored
Merge pull request #3198 from doublewhy/patch-2
Update 0027-remove-element.py
2 parents 14daefb + 02c2b65 commit 41dfdb7

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
return k
9+
10+
# Optimized solution with the same time and space complexity
11+
class Solution:
12+
def removeElement(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+
while i < n:
19+
if nums[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+
return n

0 commit comments

Comments
 (0)