forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-sum_2(AC).cpp
More file actions
52 lines (49 loc) · 1.26 KB
/
3-sum_2(AC).cpp
File metadata and controls
52 lines (49 loc) · 1.26 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
// O(1) space
#include <algorithm>
using namespace std;
class Solution {
public:
/**
* @param numbers : Give an array numbers of n integer
* @return : Find all unique triplets in the array which gives the sum of zero.
*/
vector<vector<int> > threeSum(vector<int> &nums) {
vector<int> &a = nums;
vector<int> v(3);
int n = a.size();
ans.clear();
int i, j, k;
sort(a.begin(), a.end());
int val;
i = 0;
while (i < n) {
j = i + 1;
k = n - 1;
while (j < k) {
if (a[i] + a[j] + a[k] < 0) {
++j;
} else if (a[i] + a[j] + a[k] > 0) {
--k;
} else {
v[0] = a[i];
v[1] = a[j];
v[2] = a[k];
ans.push_back(v);
val = j;
j = nextPos(a, k, j);
}
}
i = nextPos(a, n, i);
}
return ans;
}
private:
vector<vector<int> > ans;
int nextPos(vector<int> &a, int n, int i) {
int val = a[i];
while (i < n && a[i] == val) {
++i;
}
return i;
}
};