题目:
给定两个数组,返回这两个数组的交集。
解题思路:
使用哈希表用来存储第一个数组中的内容。再遍历第二个数组,看该数组的数字是否在哈希表中,在则将该数字加入输出的列表中。
代码(Python):
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
output = []
Dict = {}
for i in nums1:
if i in Dict:
Dict[i] = Dict[i]+1
else:
Dict[i] = 1
for i in nums2:
if i in Dict:
if Dict[i]>=1:
Dict[i] = Dict[i]-1
output.append(i)
continue
else:
continue
else:
continue
return output