哈希表
import java.util.HashMap;
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
/**
* 将四重循环拆分成两个双重循环,然后类似于《1. 两数之和》
* 先将两个数组的所有和的可能性res及次数添加进map
* 然后计算剩余两个数组的和是否等于0-res
*/
HashMap<Integer, Integer> map = new HashMap<>();
int n = 0;
for (int i = 0; i < nums3.length; i++) {
for (int j = 0; j < nums4.length; j++) {
map.put(nums3[i] + nums4[j], map.getOrDefault(nums3[i] + nums4[j], 0) + 1);
}
}
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
int res = nums1[i] + nums2[j];
if (map.containsKey(-res)){
n += map.get(-res);
}
}
}
return n;
}
}
/**
* 时间复杂度 O(n^2)
* 空间复杂度 O(n^2)
*/
https://leetcode-cn.com/problems/4sum-ii/