-
Notifications
You must be signed in to change notification settings - Fork 0
/
4Sum
47 lines (47 loc) · 1.75 KB
/
4Sum
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
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
if(nums.size() <= 3) return {};
vector<vector<int>> res;
sort(nums.begin(), nums.end());
int front, back;
for(int i = 0; i < nums.size();) {
for(int j = i + 1; j < nums.size();) {
front = j + 1;
back = nums.size() - 1;
while(front < back) {
int temp = nums[i] + nums[j] + nums[front] + nums[back];
if(temp == target){
vector<int> curr;
curr.push_back(nums[i]);
curr.push_back(nums[j]);
curr.push_back(nums[front]);
curr.push_back(nums[back]);
res.push_back(curr);
front++;
while(front < back && nums[front] == nums[front-1])
front++;
back--;
while(front < back && nums[back] == nums[back+1])
back--;
} else if(temp < target) {
front++;
while(front < back && nums[front] == nums[front-1])
front++;
} else {
back--;
while(front < back && nums[back] == nums[back+1])
back--;
}
}
j++;
while(j < nums.size() && nums[j] == nums[j-1])
j++;
}
i++;
while(i < nums.size() && nums[i] == nums[i-1])
i++;
}
return res;
}
};