Skip to content

Commit d15924c

Browse files
committed
remove-duplicates
1 parent e80ed18 commit d15924c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Two-pointers/easy/removeduplicate.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"Leetcode- https://leetcode.com/problems/remove-duplicates-from-sorted-array/ "
2+
'''
3+
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
4+
5+
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
6+
7+
Return k after placing the final result in the first k slots of nums.
8+
9+
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
10+
11+
Custom Judge:
12+
13+
The judge will test your solution with the following code:
14+
15+
int[] nums = [...]; // Input array
16+
int[] expectedNums = [...]; // The expected answer with correct length
17+
18+
int k = removeDuplicates(nums); // Calls your implementation
19+
20+
assert k == expectedNums.length;
21+
for (int i = 0; i < k; i++) {
22+
assert nums[i] == expectedNums[i];
23+
}
24+
If all assertions pass, then your solution will be accepted.
25+
26+
Example 1:
27+
28+
Input: nums = [1,1,2]
29+
Output: 2, nums = [1,2,_]
30+
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
31+
It does not matter what you leave beyond the returned k (hence they are underscores).
32+
'''
33+
34+
35+
def removeDuplicates(self, nums):
36+
i = 0
37+
for j in range(len(nums)):
38+
if nums[i] != nums[j]:
39+
i += 1
40+
nums[i] = nums[j]
41+
return i+1
42+
43+
#T:O(N)
44+
#S:O(1)

0 commit comments

Comments
 (0)