NYUer | LeetCode454 4Sum II

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
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228

Analysis

  1. Define a unordered_hash_map. The key is sum of each pair in nums1 and nums2. The value is the time of each pair occurs.
  2. Go through nums1 and nums2. Calculate sum of each pair and time of occurrence. Store in the unordered_hash_map.
  3. Define an integer count, which is used to count the time of n1 + n2 + n3 + n4 = 0 (also n1 + n2 = - (n3 + n4))
  4. And then, go through nums3 and nums4, if 0 - (n3 + n4) occurs in unordered_hash_map, count += unordered_hash_map[0 - (n3 + n4)]
  5. 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值