- 4Sum II 难度 中等
https://leetcode-cn.com/problems/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:
Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output: 2
Explanation:
The two tuples are:
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
Example 2:
Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
Output: 1
Constraints:
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
相关企业
- 亚马逊 Amazon|8
- Facebook|4
- 字节跳动|3
- 彭博 Bloomberg|2
相关标签
- Array
- Hash Table
相似题目
- 4Sum 中等
折半搜索 split-half, O(n^k) to O(n^(k/2))
- consider all combinations of a+b
- then consider all combinations of -c-d among those a+b
- this make O(n^4) reduce to O(n^2)
python
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
# 折半搜索 split-half O(n^k) -> O(n^(k/2)), O(n^4) -> O(n^2)
# 先找出所有A+B的combinations, 从其中找-C-D的个数
n1n2sum_combinations_ctr = dict() # {}
for n1 in nums1:
for n2 in nums2:
n1n2sum_combinations_ctr[n1+n2] = n1n2sum_combinations_ctr.get(n1+n2, 0) + 1
results_ctr = 0
for n3 in nums3:
for n4 in nums4:
# among those A+B, how many equal to -C-D?
results_ctr += n1n2sum_combinations_ctr.get(-n3-n4, 0)
return results_ctr