20
20
#include < iostream>
21
21
#include < vector>
22
22
#include < algorithm>
23
+ #include < unordered_map>
23
24
24
25
using namespace std ;
25
26
26
27
class Solution {
27
28
public:
28
29
vector<vector<int > > fourSum (vector<int > &num, int target) {
30
+ return fourSum1 (num, target);
31
+ }
32
+
33
+ vector<vector<int > > fourSum1 (vector<int > &num, int target) {
29
34
vector<vector<int > > res;
30
35
int N = num.size ();
31
36
if (N < 4 ) return res;
@@ -49,6 +54,29 @@ class Solution {
49
54
}
50
55
return res;
51
56
}
57
+
58
+ vector<vector<int > > fourSum2 (vector<int > &num, int target) {
59
+ vector<vector<int > > res;
60
+ int N = num.size ();
61
+ if (N < 4 ) return res;
62
+ unordered_multimap<int , pair<int , int > > tb;
63
+ for (int i = 0 ; i < N - 1 ; i++) {
64
+ for (int j = i + 1 ; j < N; j++) {
65
+ tb.insert (make_pair (num[i] + num[j], make_pair (i, j)));
66
+ }
67
+ }
68
+ for (auto it1 = tb.begin (); it1 != tb.end (); it1++) {
69
+ auto range = tb.equal_range (target - it1->first );
70
+ for (auto it2 = range.first ; it2 != range.second ; it2++) {
71
+ int a = it1->second .first , b = it1->second .second , c = it2->second .first , d = it2->second .second ;
72
+ if (a == c || a == d || b == c || b == d) continue ;
73
+ vector<int > path = { num[a], num[b], num[c], num[d] };
74
+ sort (begin (path), end (path));
75
+ if (find (res.begin (), res.end (), path) == res.end ()) res.push_back (path);
76
+ }
77
+ }
78
+ return res;
79
+ }
52
80
};
53
81
54
82
int main () {
0 commit comments