空间换时间,hash表2次遍历(Python)
- 潇洒解法:
利用Python的set数据结构,完成交集操作
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: return list(set(nums1) & set(nums2))
11.jpg
- 啰嗦解法(但很快)
先建立一个dict,遍历数组1,然后将数组里面的值都放到temp里面,由于dict本身不能有重复的key,相当于天然过滤掉了重复的数据此步骤约等于set(nums1)
接着就是取并集,遍历数组2,如果数组2的元素在temp里面出现,则添加到result数组中。
但是这里要注意的是,result可能重复添加
所以我们在添加一个数字到result以后,将temp里面该数字对应的value改成False,以防重复添加。
222.jpg
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: temp = {} result = [] for n in nums1: temp[n] = True for x in nums2: if temp.get(x): result.append(x) temp[x] = False return result