编程语言
首页 > 编程语言> > 0454-leetcode算法实现之四数之和II-4sum-ii-python&golang实现

0454-leetcode算法实现之四数之和II-4sum-ii-python&golang实现

作者:互联网

给你四个整数数组 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
解释:
两个元组如下:

  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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum-ii

参考:

python

# 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


golang

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
}

标签:4sum,四数,int,res,golang,nums4,nums1,nums2,nums3
来源: https://www.cnblogs.com/davis12/p/15522209.html