-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode18_4sum.cpp
124 lines (105 loc) · 3.06 KB
/
leetcode18_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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/**
* @file leetcode18_4sum.cpp
* @author wangguibao(https://github.com/wangguibao)
* @date 2021/12/12 14:59:22
* @brief https://leetcode.com/problems/4sum/
*
**/
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
class Solution {
public:
std::vector<std::vector<int>> fourSum(std::vector<int>& nums, int target) {
std::vector<std::vector<int>> ret_arrays;
if (nums.size() < 4) {
return ret_arrays;
}
std::sort(nums.begin(), nums.end());
size_t n = nums.size();
for (size_t i = 0; i < n - 3; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
long long sum = static_cast<long long int>(nums[i])
+ nums[i + 1]
+ nums[i + 2]
+ nums[i + 3];
if (sum > target) {
continue;
}
sum = static_cast<long long int>(nums[i])
+ nums[n - 1]
+ nums[n - 2]
+ nums[n - 3];
if (sum < target) {
continue;
}
for (size_t j = i + 1; j < n - 2; ++j) {
if ((j > i + 1) && (nums[j] == nums[j - 1])) {
continue;
}
size_t k = j + 1;
size_t l = n - 1;
std::set<int> past;
while (k < l) {
if (past.find(nums[k]) != past.end()) {
++k;
continue;
}
long long sum = static_cast<long long int>(nums[i])
+ nums[j]
+ nums[k]
+ nums[l];
if (sum == target) {
ret_arrays.push_back({nums[i], nums[j], nums[k], nums[l]});
past.insert(nums[k]);
--l;
++k;
} else if (sum > target) {
--l;
} else {
++k;
}
}
}
}
return ret_arrays;
}
};
int main() {
int n;
std::vector<int> nums;
while (1) {
n = 0;
std::cout << "Number of elements: ";
std::cin >> n;
if (n <= 0) {
return 0;
}
std::cout << n << " integers: " << std::endl;
nums.clear();
int ele;
for (int i = 0; i < n; ++i) {
std::cin >> ele;
nums.push_back(ele);
}
std::cout << "target: " << std::endl;
int target;
std::cin >> target;
Solution solution;
std::vector<std::vector<int>> ret_arrays = solution.fourSum(nums, target);
std::cout << "[";
for (auto vec: ret_arrays) {
std::cout << "[";
for (auto x: vec) {
std::cout << x << " ";
}
std::cout <<"]";
}
std::cout << "]" << std::endl;
}
return 0;
}