454. 4Sum II
Published in
1 min readMay 30, 2023
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
思路Coding化:
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
count = {}
#兩兩一組,先建立相加後有幾個
for i in nums1:
for j in nums2:
count[i+j] = count.get(i+j,0) + 1
#再去看剩下的nums3 nums4中,有哪些總和等於 -(i+j)
total = 0
for i in nums3:
for j in nums4:
total += count.get(-(i+j), 0)
return total
完整代碼:
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
count = {}
for i in nums1:
for j in nums2:
count[i+j] = count.get(i+j,0) + 1
total = 0
for i in nums3:
for j in nums4:
total += count.get(-(i+j), 0)
return total
Time Complexity: O(n²)
Space Complexity: O(n²)