给你四个整数数组 nums1、nums2、nums3 和 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
解释:
两个元组如下:
示例 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum-ii
参考:
# 0454.四数之和II class Solution: def fourSumCount(self, nums1: [int],nums2: [int],nums3: [int],nums4: [int]) -> int: """ 哈希策略,时间,空间O(n2) :param nums1: :param nums2: :param nums3: :param nums4: :return: """ m = dict() res = 0 for i in nums1: for j in nums2: sumAB = i + j if m.get(sumAB): m[sumAB] += 1 else: m[sumAB] = 1 for i in nums3: for j in nums4: sumCD = -(i + j) if m.get(sumCD): res += m.get(sumCD) return res
func forSumCount(nums1, nums2, nums3, nums4 []int) int { m := map[int]int{} var res int for _, v1 := range nums1 { for _, v2 := range nums2 { sumAB := v1 + v2 m[sumAB]++ } } for _, v1 := range nums3 { for _, v2 := range nums4 { sumCD := -(v1 + v2) res += m[sumCD] } } return res }