454. 4Sum II

QUESTION:

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

EXPLANATION:

因为必须4个数相加, 所以可以拆分成两个. 用一个字典来保存nums1和nums2所有可能产生的和. 然后用nums3和nums4的所有组合来看看能不能填之前的坑. 这样算出来的组合数量就是正确的了.

SOLUTION:

class Solution {
    func fourSumCount(_ nums1: [Int], _ nums2: [Int], _ nums3: [Int], _ nums4: [Int]) -> Int {
        var dic: [Int:Int] = [:]
        var result = 0
        for a in nums1 {
            for b in nums2 {
                dic[a+b, default: 0] += 1
            }
        }
        for c in nums3 {
            for d in nums4 {
                if let value = dic[-(c+d)] {
                    result += value
                }
            }
        }
        
        return result
    }
}
>