-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15_gp.cpp
55 lines (44 loc) · 1.56 KB
/
15_gp.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
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &num)
{
vector<vector<int>> res;
std::sort(num.begin(), num.end());
for (int i = 0; i < num.size(); i++)
{
int target = -num[i];
int front = i + 1;
int back = num.size() - 1;
while (front < back)
{
int sum = num[front] + num[back];
// Finding answer which start from number num[i]
if (sum < target)
front++;
else if (sum > target)
back--;
else
{
vector<int> triplet(3, 0);
triplet[0] = num[i];
triplet[1] = num[front];
triplet[2] = num[back];
res.push_back(triplet);
// Processing duplicates of Number 2
// Rolling the front pointer to the next different number forwards
while (front < back && num[front] == triplet[1]) //
front++;
// Processing duplicates of Number 3
// Rolling the back pointer to the next different number backwards
while (front < back && num[back] == triplet[2]) // remove duplicates
back--;
}
}
// Processing duplicates of Number 1
while (i + 1 < num.size() && num[i + 1] == num[i])
i++;
}
return res;
}
};