From 0905d2c7871daca4adb18566f86216a83e7894bc Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 20:46:57 -0500 Subject: [PATCH] =?UTF-8?q?Update=200454.=E5=9B=9B=E6=95=B0=E7=9B=B8?= =?UTF-8?q?=E5=8A=A0II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0454.四数相加II.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 411b60e8..7818c02b 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -125,11 +125,11 @@ class Solution { ``` Python: - +(版本一) 使用字典 ```python class Solution(object): def fourSumCount(self, nums1, nums2, nums3, nums4): - # use a dict to store the elements in nums1 and nums2 and their sum + # 使用字典存储nums1和nums2中的元素及其和 hashmap = dict() for n1 in nums1: for n2 in nums2: @@ -138,7 +138,7 @@ class Solution(object): else: hashmap[n1+n2] = 1 - # if the -(a+b) exists in nums3 and nums4, we shall add the count + # 如果 -(n1+n2) 存在于nums3和nums4, 存入结果 count = 0 for n3 in nums3: for n4 in nums4: @@ -149,20 +149,18 @@ class Solution(object): ``` - +(版本二)使用 defaultdict ```python +from collections import defaultdict class Solution: def fourSumCount(self, nums1: list, nums2: list, nums3: list, nums4: list) -> int: - from collections import defaultdict # You may use normal dict instead. rec, cnt = defaultdict(lambda : 0), 0 - # To store the summary of all the possible combinations of nums1 & nums2, together with their frequencies. for i in nums1: for j in nums2: rec[i+j] += 1 - # To add up the frequencies if the corresponding value occurs in the dictionary for i in nums3: for j in nums4: - cnt += rec.get(-(i+j), 0) # No matched key, return 0. + cnt += rec.get(-(i+j), 0) return cnt ```