题目链接:https://leetcode.cn/problems/4sum-ii/description/

核心思想:哈希法-dict (字典)

解析:

  • 定义一个空字典 hashmap = dict()

  • 遍历前两个列表,相加后 统计hashmap[a+b] 的出现次数,a+b用来与后 两个列表遍历时 进行匹配

  • 遍历后两个列表,查看hashmap [-c-d]是否在hashmap出现过(因为a+b+c+d = 0 -> a+b = -c-d),如果出现过,count += hashmap[-c-d]

class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        hashmap = dict()
        for n1 in nums1:
            for n2 in nums2:
                if n1+n2 in hashmap:
                    hashmap[n1+n2] += 1
                else:
                    hashmap[n1+n2] = 1 

        count = 0
        for n3 in nums3:
            for n4 in nums4:
                key = -n3-n4
                if key in hashmap:
                    count += hashmap[key]
        return count

注意:直接使用 hashmap[n1 + n2] += 1 是不行的,因为如果 n1 + n2 这个键(key)在 hashmap 中不存在,Python 会抛出 KeyError 异常,所以不存在时先赋值为 1