来源:
题目描述:
思路:
代码随想录:
- 选择unordered_map数据结构,key放1,2两数之和,value放1和2两数之和出现的次数。
- 遍历1,2数组,统计两数组元素之和和出现的次数 放到map中
- 遍历CD数组,找到target-(3+4)在map中如果出现,则把key对应的value放到count中
- 返回count
代码实现:
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int,int> map;//key:1+2的数值,value:1+2数值出现的次数
// 遍历1和2数组,统计两个数组元素之和,和出现的次数,放到map中
for(int a : nums1){
for(int b : nums2){
map[a + b]++;
}
}
int count = 0;// 统计a+b+c+d = 0 出现的次数
for(int c : nums3){
for(int d : nums4){
if(map.find(0-(c+d)) != map.end()){
count+=map[0-(c+d)];
}
}
}
return count;
}
};