-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15-3sum.cpp
More file actions
48 lines (46 loc) · 1.48 KB
/
Copy path15-3sum.cpp
File metadata and controls
48 lines (46 loc) · 1.48 KB
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
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<int> nums2;
unordered_map<int,int> freq;
for (auto n : nums) {
freq[n]++;
if (freq[n] < 4) {
nums2.push_back(n);
}
}
nums = nums2;
sort(nums.begin(), nums.end());
vector<vector<int>> solutions;
for (int i = 0; i < nums.size() - 2; i++) {
int j = i + 1;
int k = nums.size() - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0) {
vector<int> curr;
curr.push_back(nums[i]);
curr.push_back(nums[j]);
curr.push_back(nums[k]);
solutions.push_back(curr);
j++;
k--;
} else if (sum < 0) {
j++;
} else
k--;
}
}
for (auto& c : solutions) {
sort(c.begin(), c.end());
}
sort(solutions.begin(), solutions.end());
auto it = unique(solutions.begin(), solutions.end(),
[](vector<int> a, vector<int> b) {
return ((a[1] == b[1]) && (a[2] == b[2]) &&
(a[0] == b[0]));
});
solutions.erase(it, solutions.end());
return solutions;
}
};