forked from changqing16/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15_c.cpp
More file actions
62 lines (48 loc) · 1.52 KB
/
15_c.cpp
File metadata and controls
62 lines (48 loc) · 1.52 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <algorithm>
#include <vector>
using namespace std;
//不一定比我写的快
vector<vector<int>> threeSum(vector<int> &nums)
{
vector<vector<int>> res;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++)
{
int target = -nums[i];
int front = i + 1;
int back = nums.size() - 1;
if (target < 0)
{
break;
}
while (front < back)
{
int sum = nums[front] + nums[back];
// Finding answer which start from number nums[i]
if (sum < target)
front++;
else if (sum > target)
back--;
else
{
vector<int> triplet(3, 0);
triplet[0] = nums[i];
triplet[1] = nums[front];
triplet[2] = nums[back];
res.push_back(triplet);
// Processing duplicates of Number 2
// Rolling the front pointer to the next different number forwards
while (front < back && nums[front] == triplet[1])
front++;
// Processing duplicates of Number 3
// Rolling the back pointer to the next different number backwards
while (front < back && nums[back] == triplet[2])
back--;
}
}
// Processing duplicates of Number 1
while (i + 1 < nums.size() && nums[i + 1] == nums[i])
i++;
}
return res;
}