-
Notifications
You must be signed in to change notification settings - Fork 0
/
18_4Sum.cpp
52 lines (49 loc) · 1.77 KB
/
18_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
52
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
if(nums.empty())
return res;
sort(nums.begin(),nums.end());
int n=nums.size();
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
int target_2=target-nums[j]-nums[i];
int front = j+1;
int back = n-1;
while(front<back)
{
int two_sum = nums[front]+nums[back];
if(two_sum<target_2)
front++;
else if(two_sum>target_2)
back--;
else
{
vector<int> quadruplet(4,0);
quadruplet[0]=nums[i];
quadruplet[1]=nums[j];
quadruplet[2]=nums[front];
quadruplet[3]=nums[back];
res.push_back(quadruplet);
//processing the duplicates of number 3
while(front<back && nums[front]==quadruplet[2])
++front;
//processing the duplicates of number 4
while(front<back && nums[back]==quadruplet[3])
--back;
}
}
////processing the duplicates of j
while(j+1<n && nums[j+1]==nums[j])
++j;
}
//processing the duplicates of i
while(i+1<n && nums[i+1]==nums[i])
++i;
}
return res;
}
};