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 ```