-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC++
More file actions
33 lines (29 loc) · 647 Bytes
/
Copy pathC++
File metadata and controls
33 lines (29 loc) · 647 Bytes
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
# C++
1. Brute-Force Approach :
class Solution {
public:
int removeDuplicates(std::vector<int>& nums) {
int k = 1, n = nums.size();
for (int i = 1; i < n; ++i) {
if (nums[i - 1] != nums[i]) {
nums[k] = nums[i];
++k;
}
}
return k;
}
};
2. Optimal Approach :
class Solution {
public:
int removeDuplicates(std::vector<int>& nums) {
std::unordered_set<int> set;
int k = 0;
for (int num : nums) {
if (set.insert(num).second) {
nums[k++] = num;
}
}
return k;
}
};