454. 四数相加 II

454. 四数相加 II

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

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

示例 1:

输入: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

示例 2:

输入:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
输出:1

  提示:

  • n == nums1.length
  • n == nums2.length
  • n == nums3.length
  • n == nums4.length
  • 1 <= n <= 200
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
/**
2024年7月22日20:23:11
思路:通过Map,把nums1和nums2先进行加和,再把nums3和nums4进行加和
就能把时间复杂度降为n^2
 */
class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer,Integer> map = new HashMap<>();
        int res = 0;
        for(int i : nums1){
            for(int j : nums2){
                int temp = i + j;
                if(map.containsKey(temp)){
                    map.put(temp,map.get(temp) + 1);
                } else{
                    map.put(temp,1);
                }
            }
        }

        for(int i : nums3){
            for(int j : nums4){
                int temp = 0 -(i + j);
                if(map.containsKey(temp)){
                    res += map.get(temp) ;
                }
            }
        }
        return res;
    }
}

相关推荐

  1. 454. 相加 II

    2024-07-23 01:44:03       15 阅读
  2. 【Leetcode】454. 相加 II

    2024-07-23 01:44:03       45 阅读
  3. 【LeetCode】454. 相加 II

    2024-07-23 01:44:03       30 阅读
  4. 454.相加

    2024-07-23 01:44:03       40 阅读
  5. LeetCode454 相加

    2024-07-23 01:44:03       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-23 01:44:03       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-23 01:44:03       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-23 01:44:03       45 阅读
  4. Python语言-面向对象

    2024-07-23 01:44:03       55 阅读

热门阅读

  1. windows update 1053

    2024-07-23 01:44:03       14 阅读
  2. HTML5+ push消息推送

    2024-07-23 01:44:03       13 阅读
  3. Composition API实现逻辑复用

    2024-07-23 01:44:03       14 阅读
  4. 云计算安全技术介绍

    2024-07-23 01:44:03       16 阅读
  5. 杭电第一场

    2024-07-23 01:44:03       15 阅读
  6. Cow coupons

    2024-07-23 01:44:03       14 阅读