-
Notifications
You must be signed in to change notification settings - Fork 0
/
80_Remove Duplicates from Sorted Array II.cpp
85 lines (80 loc) · 1.76 KB
/
80_Remove Duplicates from Sorted Array II.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return removeDuplicatesNum(nums, 2);
}
int removeDuplicatesNum(vector<int>& nums, int k) {
int len = nums.size();
if (len < k) return len;
int new_tail = 1, tail = 1;
int cnt = 1;
while (tail < len) {
if (nums[tail] != nums[tail-1]) {
cnt = 1;
nums[new_tail] = nums[tail];
new_tail++;
} else {
if (cnt < k) {
cnt++;
nums[new_tail] = nums[tail];
new_tail++;
}
}
tail++;
}
return new_tail;
}
int removeDuplicatesNum(vector<int>& nums, int k) {
int len = nums.size();
if (len < k) return len;
int tail = 1, new_tail = 1;
int cnt = 1;
while (tail < len) {
if (nums[tail] != nums[tail-1]) {
cnt = 1;
nums[new_tail] = nums[tail];
new_tail++;
} else {
if (cnt < k) {
cnt++;
nums[new_tail] = nums[tail];
new_tail++;
}
}
tail++;
}
return new_tail;
}
};
int main() {
Solution s;
int n;
while (cin >> n) {
vector<int> nums(n);
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}
cout << s.removeDuplicates(nums) << endl;
for (int i = 0; i < nums.size(); ++i) {
cout << nums[i] << " ";
}
cout << endl;
}
return 0;
}
/**
6
1 1 1 2 2 3
5
3
1 1 1
2
9
0 0 1 1 1 1 2 3 3
7
3
1 1 1
2
*/