0454-leetcode算法实现之四数之和II-4sum-ii-python&golang实现
2021/11/8 1:10:16
本文主要是介绍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
解释:
两个元组如下:
- (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
- (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
参考:
- https://leetcode-cn.com/problems/4sum-ii/solution/chao-ji-rong-yi-li-jie-de-fang-fa-si-shu-xiang-jia/
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 }
这篇关于0454-leetcode算法实现之四数之和II-4sum-ii-python&golang实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型