Leecode 0454. 4Sum II
454. 4Sum II
Given four integer arrays nums1
, nums2
, nums3
, and nums4
all of length n
, return the number of tuples (i, j, k, l)
such that:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
Example 1:
1 | Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] |
Example 2:
1 | Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] |
题目大意
给定四个长度相同的整数数组 nums1、nums2、nums3 和 nums4,返回满足 nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
的元组 (i, j, k, l) 的数量。
解题思路
采用哈希表分治的方法,将四数之和问题拆分为两数之和问题:
- 计算 nums1 和 nums2 中所有可能的两数之和,并将其出现次数存储在哈希表中。
- 计算 nums3 和 nums4 中所有可能的两数之和,然后查找哈希表中是否存在该和的相反数。
- 累计所有满足条件的组合数量。
这种方法将时间复杂度从 O (n⁴) 降低到 O (n²)。
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.