-
Notifications
You must be signed in to change notification settings - Fork 1
/
15.三数之和.cpp
76 lines (70 loc) · 1.38 KB
/
15.三数之和.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
/*
* @lc app=leetcode.cn id=15 lang=cpp
*
* [15] 三数之和
*/
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
// @lc code=start
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &nums)
{
sort(nums.begin(), nums.end());
int target = 0;
vector<vector<int>> res;
for (int i = 0; i < nums.size(); i++)
{
twoSum(nums, i, target - nums[i], res);
while (i < nums.size() - 1 && nums[i] == nums[i + 1])
{
i++;
}
}
return res;
}
void twoSum(vector<int> &nums, int startIdx, int target, vector<vector<int>> &res)
{
int l = startIdx + 1, h = nums.size() - 1;
while (l < h)
{
int left = nums[l], right = nums[h];
int sum = left + right;
if (sum < target)
{
while (l < h && left == nums[l])
l++;
}
else if (sum > target)
while (l < h && right == nums[h])
h--;
else
{
res.push_back({nums[startIdx], left, right});
while (l < h && left == nums[l])
l++;
while (l < h && right == nums[h])
h--;
}
}
}
};
// @lc code=end
int main()
{
Solution s;
vector<int> nums = {};
vector<vector<int>> sol = s.threeSum(nums);
for (auto i : sol)
{
cout << '{';
for (auto j : i)
cout << j << ',';
cout << '}';
}
cout << endl;
return 0;
}