Skip to content

Commit ba67a80

Browse files
committed
Create remove-duplicates-from-sorted-array-ii.cpp
1 parent a17350d commit ba67a80

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int removeDuplicates(vector<int>& nums) {
7+
if (nums.empty()) {
8+
return 0;
9+
}
10+
11+
const int k = 2; // At most k duplicated.
12+
13+
int left = 0;
14+
int right = 1;
15+
16+
while (right < nums.size()) {
17+
if (nums[left] != nums[right] ||
18+
(left - k + 1 < 0 || nums[left] != nums[left - k + 1])) {
19+
++left;
20+
nums[left] = nums[right];
21+
}
22+
++right;
23+
}
24+
25+
return left + 1;
26+
}
27+
};

0 commit comments

Comments
 (0)