Update 0454.四数相加II.md

This commit is contained in:
jianghongcheng
2023-05-05 20:53:12 -05:00
committed by GitHub
parent 0905d2c787
commit 5cff41ab09

View File

@@ -149,7 +149,29 @@ class Solution(object):
```
(版本二)使用 defaultdict
(版本二) 使用字典
```python
class Solution(object):
def fourSumCount(self, nums1, nums2, nums3, nums4):
# 使用字典存储nums1和nums2中的元素及其和
hashmap = dict()
for n1 in nums1:
for n2 in nums2:
hashmap[n1+n2] = hashmap.get(n1+n2, 0) + 1
# 如果 -(n1+n2) 存在于nums3和nums4, 存入结果
count = 0
for n3 in nums3:
for n4 in nums4:
key = - n3 - n4
if key in hashmap:
count += hashmap[key]
return count
```
(版本三)使用 defaultdict
```python
from collections import defaultdict
class Solution: