四数之和

题目:

四数之和

解法-哈希表

思路:
只要找到A[i] + B[j] + C[k] + D[l] = 0就可以,不用考虑有重复的四个元素相加等于0的情况

  1. 首先定义 一个unordered_map,key放a和b两数之和,value 放a和b两数之和出现的次数
  2. 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中
  3. 定义int变量count,用来统计 a+b+c+d = 0 出现的次数
  4. 再遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来
  5. 最后返回统计值 count 就可以了

复杂度:

  • 时间复杂度:
  • 空间复杂度:

代码:

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
#include <vector>
#include <unordered_map>
#include <iostream>
using namespace std;
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> umap; //key:a+b的数值,value:a+b数值出现的次数
// 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中
//注意:umap初始值为空,所以umap[a+b]++是1,如果再次出现相同的a+b,那么umap[a+b]++就是2
for (int a : A) {
for (int b : B) {
umap[a + b]++;
cout <<"a="<<a<<"b="<<b<<"umap[" <<a+b<<"] = "<<umap[a+b]<<endl;
}
}
//遍历umap
for(auto i:umap)
{
cout<<"i.first="<<i.first<<" i.second="<<i.second<<endl;
}
int count = 0; // 统计a+b+c+d = 0 出现的次数
// 再遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来。
for (int c : C) {
for (int d : D) {
//如果在umap中找到0-(c+d)这个key,那么就把对应的value也就是出现次数统计出来
if (umap.find(0 - (c + d)) != umap.end()) {
count += umap[0 - (c + d)];
}
}
}
return count;
}
};
// 单元测试
int main() {
Solution solution;
vector<int> A = {1, 2};
vector<int> B = {-2, -1};
vector<int> C = {-1, 2};
vector<int> D = {0, 2};

int result = solution.fourSumCount(A, B, C, D);
cout << "The count of four sum is: " << result << endl; // 应输出 2

return 0;
}

语法小点:

  1. 解释:umap[a + b]++;
    • umap初始值为空,所以umap[a+b]++是1,如果再次出现相同的a+b,那么umap[a+b]++就是2
  2. *
    *