题目:
给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
解题思路:
不可取的思路:初步看题目,在不考虑时间复杂度的情况下,我们可以选择大力出奇迹,来一个四重 for 循环,轻松搞定这个中等题,实际上并不能通过。
正确思路之一:尽可能降低时间复杂度,这题有四个数组,做法是只遍历两个数组,统计任意前面两个数组元素的两两之和 temp1 ,存进 HashMap 中,key 为前面两个数组元素的两两之和 temp1 ,value 为两两之和出现的次数。再遍历剩下两个数组元素的两两之和 temp2 ,计算 0 与 temp2 的差值 0 - temp2 ,并查看存放前面两个数组元素两两之和的 HashMap 中是否存在 0 -temp2 ,如果存在,则取出其对应的 valule 值,并相加。相加的总和为题目所求的结果。
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
int res = 0;
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int data1 : nums1){
for(int data2 : nums2){
//统计前两个数组中所有元素的和,设为key,每个和出现的次数设为value
int temp1 = data1 + data2;
if(map.containsKey(temp1)){
map.put(temp1,map.get(temp1) + 1);
} else {
map.put(temp1,1);
}
}
}
for(int data3 : nums3){
for(int data4 : nums4){
//计算剩余两个元素的和与0的差是否包含在map中,如果在,则加上对应的value值
int temp2 = data3 + data4;
if(map.containsKey(0 - temp2)){
res += map.get(0 - temp2);
}
}
}
return res;
}
}