LC454-四数相加

力扣题目链接

给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:

0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

示例:

输入:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
输出:2
解释:
两个元组如下:

  1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
  2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

思路:

假如是数组A,B,C,D

  1. 首先定义 一个Hashmap,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 就可以了

注:使用暴力破解用四个for循环那可太慢了,万一数组元素多指不定还超时,因此这个方法不适用。

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer,Integer> map=new HashMap<>();
        int count=0;
        int temp; //存放两数之和,后面作为key
        for(int i:nums1){
            for(int j:nums2){
                temp=i+j;
                if(map.containsKey(temp))
                {
                    map.put(temp,map.get(temp)+1);
                }
                else{
                    map.put(temp,1); //如果没有这个key则保存值为1
                }
            }
        }
        for(int i:nums3){
            for(int j:nums4){
                temp=i+j;
                if(map.containsKey(0-temp))
                {
                    count+=map.get(0-temp);
                }
            }
        }
        return count;

    }
}
posted @ 2022-04-09 18:11  贝贝子  阅读(29)  评论(0编辑  收藏  举报