应用题-哈希表-四数相加II ( 处理方式请注意 )

管理员
```python from collections import defaultdict class Solution: # 给你四个整数数组nums1、nums2、nums3和nums4,数组长度都是n,请你计算有多少个元组(i, j, k, l)能满足: # 0 <= i, j, k, l < n # nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 # 1 <= n <= 200 def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int: # 从数据规模来看 最多也就是两层循环 # 这样处理 (只需要知道个数就行): # 1. 构造map: key是nums1加nums2的和 value是和出现的次数 # 2. 定义count,用来统计 a+b+c+d = 0 出现的次数 # - 遍历nums3加nums4的和,寻找0-(c+d)是否在map中出现,若出现统计次数 ab_map = defaultdict( int ) for a in nums1: for b in nums2: ab_map[ a + b ] += 1 count = 0 for c in nums3: for d in nums4: if ( 0 - c - d ) in ab_map: count += ab_map[ ( 0 - c - d ) ] return count ```
评论 0

发表评论 取消回复

Shift+Enter 换行  ·  Enter 发送
还没有评论,来发表第一条吧