-
Notifications
You must be signed in to change notification settings - Fork 0
/
3SUM.cpp
73 lines (65 loc) · 1.79 KB
/
3SUM.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
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(num.begin(), num.end());
vector<vector<int>> ans;
int i =0, j =0, k = 0;
int lastNum = 0;
for (i = 0; i < num.size(); i++)
{
while (i > 0 && num[i] == num[i - 1])
{
i++;
if (i >= num.size())
{
break;
}
}
if (i >= num.size())
{
break;
}
j = i + 1;
k = num.size() - 1;
while (j < k)
{
while(j > i + 1 && num[j] == num[j - 1])
{
j++;
if (j >= k)
{
break;
}
}
if (j >= k)
{
break;
}
if (num[i] + num[j] + num[k] == 0)
{
vector<int> temp;
temp.push_back(num[i]);
temp.push_back(num[j]);
temp.push_back(num[k]);
ans.push_back(temp);
j++;
k--;
}
else
{
if (num[i] + num[j] + num[k] < 0)
{
j++;
}
else
{
k--;
}
}
}
}
return ans;
}
};