-
Notifications
You must be signed in to change notification settings - Fork 3
/
4sum.cpp
51 lines (43 loc) · 1.34 KB
/
4sum.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
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int> > ans;
int n = nums.size();
if(n == 0)
return ans;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
int sum = target - (nums[i] + nums[j]);
int lo = j+1;
int hi = n-1;
while(lo < hi)
{
int lohi = nums[lo] + nums[hi];
if(lohi < sum)
lo++;
else if(lohi > sum)
hi--;
else
{
vector<int> t(4,0);
t[0] = nums[i];
t[1] = nums[j];
t[2] = nums[lo];
t[3] = nums[hi];
ans.push_back(t);
while(lo<hi && nums[lo] == t[2])
lo++;
while(lo < hi && nums[hi] == t[3])
hi--;
}
}
while(j+1 < n && nums[j] == nums[j+1]) ++j;
}
while(i+1 < n && nums[i] == nums[i+1]) ++i;
}
return ans;
}
};