Algorithm Puzzles: Remove Duplicates from Sorted Array II

Algorithm Puzzles everyday every week sometimes: Remove Duplicates from Sorted Array II

Puzzle

Puzzle from leetcode:

Solution

Two pointer + iterator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int removeDuplicates(vector<int>& nums) const {
auto left = nums.begin();
auto right = left + 1;
auto end = nums.end();
int occurred = 0;

for(; right != end; ++right) {
if(*right == *left) {
if(occurred > 0) {
continue;
} else {
occurred++;
}
} else {
occurred = 0;
}
left++;
*left = *right;
}

return std::distance(nums.begin(), left) + 1;
}
};

T.C.: O(N)