题目描述
给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
求解思路
-
可以考虑将四个数组分成两部分:A+B 和 C+D;
-
将 A+B 的和存放在HashMap中,其中Key是和,Value是出现次数;
-
因为题目要求是四个数相加为0,所以我们需要在C+D中找 0-(A+B)-----》tem,如果在HashMap中能够匹配到 tem 的话,将结果res + tem.value 更新;
-
res不是+1更新,因为在HashMap中 tem 的值可能为多个,我们最终要统计他的出现次数。
输入输出示例
代码
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer,Integer> map = new HashMap<>();
int tem;
int res = 0;
for(int i : nums1){
for(int j : nums2){
tem = i + j;
if(map.containsKey(tem)){
map.put(tem,map.get(tem)+1);
}else{
map.put(tem,1);
}
}
}
for(int i : nums3){
for(int j : nums4){
tem = i + j;
if(map.containsKey(-tem)){
res += map.get(-tem);
}
}
}
return res;
}
}