-
Notifications
You must be signed in to change notification settings - Fork 0
/
18. 4Sum.cpp
55 lines (38 loc) · 1.61 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
53
54
55
/*
Problem Link: https://leetcode.com/problems/4sum/
Time: 51 ms (Beats 88.4%), Space: 13.2 MB (Beats 87.57%)
*/
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++) {
long long rem = (long long)target - (long long)nums[i] - (long long)nums[j];
int start= j + 1;
int end= n - 1;
while(start < end) {
int two_sum = nums[start] + nums[end];
if (two_sum < rem) start++;
else if (two_sum > rem) end--;
else {
vector<int> ans(4, 0);
ans[0] = nums[i];
ans[1] = nums[j];
ans[2] = nums[start];
ans[3] = nums[end];
res.push_back(ans);
while (start < end && nums[start] == ans[2]) ++start;
while (start < end && nums[end] == ans[3]) --end;
}
}
while(j+1 < n && nums[j + 1] == nums[j]) ++j;
}
while (i+1 < n && nums[i + 1] == nums[i]) ++i;
}
return res;
}
};