Skip to content

Commit 79f186e

Browse files
Merge pull request #2788 from Piyush-Deshmukh/patch-1
Create 0080-remove-duplicates-from-sorted-array-ii.cpp
2 parents c9be593 + 519eb2a commit 79f186e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
Given a sorted array nums, remove some duplicates in-place such that each unique element appears at most twice.
3+
Ex:- nums = [1,1,1,2,2,3] -> [1,1,2,2,3,_]
4+
5+
Input -> nums = [1,1,1,2,2,3]
6+
Output -> 5
7+
8+
Use two pointers to find at most 2 duplicates.
9+
10+
Time - O(n)
11+
Space - O(1)
12+
*/
13+
14+
class Solution {
15+
public:
16+
int removeDuplicates(vector<int>& nums) {
17+
int k = 2; // define at most k times of duplicate numbers
18+
19+
int l = 1, count = 1;
20+
21+
for(int r = 1; r < nums.size(); r++){
22+
if(nums[r] == nums[r-1]){
23+
if(count < k)
24+
nums[l++] = nums[r];
25+
count++;
26+
}
27+
else {
28+
count = 1;
29+
nums[l++] = nums[r];
30+
}
31+
}
32+
33+
return l;
34+
}
35+
};

0 commit comments

Comments
 (0)