-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3Sum.cpp
More file actions
39 lines (37 loc) · 1.08 KB
/
3Sum.cpp
File metadata and controls
39 lines (37 loc) · 1.08 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
/*
Given an integer array nums, return all the triplets
[nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k,
and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Constraints:
3 <= nums.length <= 3000
-105 <= nums[i] <= 105
*/
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int target = 0;
sort(nums.begin(), nums.end());
set<vector<int>> s;
vector<vector<int>> output;
for (int i = 0; i < nums.size(); i++){
int j = i + 1;
int k = nums.size() - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == target) {
s.insert({nums[i], nums[j], nums[k]});
j++;
k--;
} else if (sum < target) {
j++;
} else {
k--;
}
}
}
for(auto triplets : s)
output.push_back(triplets);
return output;
}
};