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 69d1678

Browse files
Implement removeDuplicates function to eliminate duplicates from a sorted array
1 parent 70e97e6 commit 69d1678

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
'''
2+
You are given an integer array nums sorted in non-decreasing order. Your task is to remove duplicates from nums in-place so that each element appears only once.
3+
4+
After removing the duplicates, return the number of unique elements, denoted as k, such that the first k elements of nums contain the unique elements.
5+
6+
Note:
7+
8+
The order of the unique elements should remain the same as in the original array.
9+
It is not necessary to consider elements beyond the first k positions of the array.
10+
To be accepted, the first k elements of nums must contain all the unique elements.
11+
Return k as the final result.
12+
13+
Example 1:
14+
15+
Input: nums = [1,1,2,3,4]
16+
17+
Output: [1,2,3,4]
18+
Explanation: You should return k = 4 as we have four unique elements.
19+
20+
Example 2:
21+
22+
Input: nums = [2,10,10,30,30,30]
23+
24+
Output: [2,10,30]
25+
Explanation: You should return k = 3 as we have three unique elements.
26+
27+
Constraints:
28+
29+
1 <= nums.length <= 30,000
30+
-100 <= nums[i] <= 100
31+
nums is sorted in non-decreasing order.
32+
'''
33+
34+
# Solution using set to remove duplicates and then sorting the unique elements
35+
class Solution:
36+
def removeDuplicates(self, nums):
37+
final_set = sorted(set(nums))
38+
nums[:len(final_set)] = final_set
39+
return len(final_set)

0 commit comments

Comments
(0)

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