from typing import List
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
# 記錄兩個數組中每個數字出現的次數
result1 = {}
result2 = {}
# 遍歷兩個數組,然後將其數字出現次數添加入字典中
for i in nums1:
if i not in result1.keys():
result1[i] = 1
else:
result1[i] += 1
for i in nums2:
if i not in result2.keys():
result2[i] = 1
else:
result2[i] += 1
# 將兩個字典的鍵取出
k1 = [i for i in result1.keys()]
k2 = [i for i in result2.keys()]
# 求兩個字典鍵的交集
k = set(k1) & set(k2)
# 結果列表
r = []
# 同一個鍵,代表兩個列表中都有出現,然後取最小的值爲出現的次數,然後用列表的extend方法添加入結果列表中
for i in k:
m = min(result1[i], result2[i])
r.extend([i]*m)
return r
if __name__ == "__main__":
s = Solution()
nums1 = [1,2,2,1]
nums2 = [2,2]
r1 = s.intersect(nums1, nums2)
print(r1)
給定兩個數組,編寫一個函數來計算它們的交集。
感覺只要用字典,速度都不會慢,因爲字典查找遍歷都好快