Skip to content

Commit 0e50dca

Browse files
committed
D. J.:
- Added leetcode problem and solution for 80. Remove Duplicates from Sorted Array II
1 parent 58b324f commit 0e50dca

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def removeDuplicates(self, nums: List[int]) -> int:
6+
"""
7+
Given an integer array nums sorted in non-decreasing order, remove some duplicates
8+
in-place such that each unique element appears at most twice.
9+
The relative order of the elements should be kept the same.
10+
11+
Since it is impossible to change the length of the array in some languages, you must instead
12+
have the result be placed in the first part of the array nums.
13+
More formally, if there are k elements after removing the duplicates, then the first k elements
14+
of nums should hold the final result. It does not matter what you leave beyond the first k elements.
15+
16+
Return k after placing the final result in the first k slots of nums.
17+
18+
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
19+
"""
20+
left = 1
21+
right = 1
22+
length = 1
23+
second_val = True
24+
val_before = nums[0]
25+
while right < len(nums):
26+
if second_val and val_before == nums[right]:
27+
nums[left] = nums[right]
28+
val_before = nums[left]
29+
second_val = False
30+
left += 1
31+
right += 1
32+
length += 1
33+
elif val_before == nums[right]:
34+
right += 1
35+
else:
36+
nums[left] = nums[right]
37+
val_before = nums[left]
38+
second_val = True
39+
left += 1
40+
right += 1
41+
length += 1
42+
return length
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._80_remove_duplicates_from_sorted_array_II import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "expected"],
10+
argvalues=[
11+
([1, 1, 1, 2, 2, 3], [1, 1, 2, 2, 3]),
12+
([0, 0, 1, 1, 1, 1, 2, 3, 3], [0, 0, 1, 1, 2, 3, 3]),
13+
],
14+
)
15+
def test_func(nums: List[int], expected: List[int]):
16+
length = Solution().removeDuplicates(nums)
17+
assert nums[:length] == expected

0 commit comments

Comments
 (0)