種類 : hash table
難度 : medium
題目 : 454. 4Sum II
思維邏輯
將四個list轉為set(❌錯誤)
- 歷遍四個
set
歷遍前兩個list,將和與次數紀錄在dict
- 歷遍後兩個
list,若兩元素相加 * -1在dict中,count += dict[元素相加*-1]
解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution: def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int: d = dict() for n1 in nums1: for n2 in nums2: if n1+n2 in d: d[n1+n2] += 1 else: d[n1+n2] = 1
count = 0 for n3 in nums3: for n4 in nums4: if (n3 + n4)*-1 in d: count += d[(n3 + n4)*-1]
return count
|
四個list長度: n
時間複雜度: O(2n2) -> O(n2)
空間複雜度: O(2n2) -> O(n2)
難點
- 四個
list如何有效的計算並累加次數
最佳解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| """ 字典 dict可設定default, 省略if...else """ class Solution(object): def fourSumCount(self, nums1, nums2, nums3, nums4): hashmap = dict() for n1 in nums1: for n2 in nums2: hashmap[n1+n2] = hashmap.get(n1+n2, 0) + 1 count = 0 for n3 in nums3: for n4 in nums4: key = - n3 - n4 if key in hashmap: count += hashmap[key] return count
|
時間複雜度: O(n2)
空間複雜度: O(n2)