LeetCode454 4Sum II
Author: Stefan Su
Create time: 2022-10-31 15:16:25
Location: New York City, NY, USA
Description Medium
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
Constrains
n == nums1.length
n == nums2.length
n == nums3.length
n == nums4.length
1 <= n <= 200
-2
28<= nums1[i], nums2[i], nums3[i], nums4[i] <= 2
28
Analysis
- Define a
unordered_hash_map
. The key is sum of each pair innums1
andnums2
. The value is the time of each pair occurs. - Go through
nums1
andnums2
. Calculate sum of each pair and time of occurrence. Store in theunordered_hash_map
. - Define an integer
count
, which is used to count the time ofn1 + n2 + n3 + n4 = 0
(alson1 + n2 = - (n3 + n4)
) - And then, go through
nums3
andnums4
, if0 - (n3 + n4)
occurs inunordered_hash_map
,count += unordered_hash_map[0 - (n3 + n4)]
- Return
count
Solution
- unordered hash map version
class Solution(object):
def fourSumCount(self, nums1, nums2, nums3, nums4):
"""
:type nums1: List[int]
:type nums2: List[int]
:type nums3: List[int]
:type nums4: List[int]
:rtype: int
"""
unordered_hash_map = dict()
# use unordered hash map to store the sum of each element in nums1 and nums2
# key is sum, value is how much time the value of the sum occurs
for n1 in nums1:
for n2 in nums2:
if n1 + n2 in unordered_hash_map:
unordered_hash_map[n1 + n2] += 1
else:
unordered_hash_map[n1 + n2] = 1
# if [0 - (n1 + n2)] exists in (-nums3[i] - nums4[j]), then increment count by 1
count = 0
for n3 in nums3:
for n4 in nums4:
key = -n3 - n4
if key in unordered_hash_map:
count += unordered_hash_map[key]
return count
Hopefully, this blog can inspire you when solving LeetCode454. For any questions, please comment below.