第二十二天 Intersection of Two Arrays
2018-09-11 本文已影响0人
业余马拉松选手
哈哈,一天刷两道水题,也是很开心的一件事呢。【总是让我想到一年逛两次海澜之家。。。】
https://leetcode-cn.com/problems/intersection-of-two-arrays/description/
继续求两个数组的交集,这次要求一个数字只出现一次
那么直接就能想到set这种数据结构咯
方法还是先遍历一个数组,得到总共出现的数字的set,然后再遍历第二个数组,遍历的时候看这个数字是否出现过,如果出现过也放到另一个set内,最后都遍历结束了,返回第二个set,这里要注意下类型转换下
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = set()
hash_set = set()
for i in nums1:
hash_set.add(i)
for i in nums2:
if i in hash_set:
result.add(i)
return list(result)
方法是很直接咯,嗯,其实还可以用python的内置函数,感觉那是作弊🤦