Skip to content

Commit 58b324f

Browse files
committed
D. J.:
- Added leetcode problem and solution for 26. Remove Duplicates from Sorted Array
1 parent 49246ba commit 58b324f

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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,
8+
remove the duplicates in-place such that each unique element appears only once.
9+
The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
10+
11+
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
12+
- Change the array nums such that the first k elements of nums contain the unique elements in the order they
13+
were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
14+
- Return k.
15+
"""
16+
left, right, length, val_before = 1, 1, 1, nums[0]
17+
while right < len(nums):
18+
if val_before == nums[right]:
19+
right += 1
20+
else:
21+
nums[left] = nums[right]
22+
val_before = nums[left]
23+
left += 1
24+
right += 1
25+
length += 1
26+
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._26_remove_duplicates_from_sorted_array import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "expected"],
10+
argvalues=[
11+
([1, 1, 2], [1, 2]),
12+
([0, 0, 1, 1, 1, 2, 2, 3, 3, 4], [0, 1, 2, 3, 4]),
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)