leetcode第350题,要求求两个集合的交集。集合内元素可任意重复。结果可以以任意顺序给出。
tag下有很多方法,我第一反应就是用hash表,思路也比较简单,就是先用hash扫一遍第一个集合,记录一下,然后扫第二个集合,如果遇到相同的,就加入结果列表,同时hash值自动递减,直到0,说明没有此元素了。
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
hash = {}
n1 = len(nums1)
n2 = len(nums2)
ans = []
for i in range(n1):
if nums1[i] in hash:
hash[nums1[i]] += 1
else:
hash[nums1[i]] = 1
for i in range(n2):
if nums2[i] in hash:
if hash[nums2[i]] != 0:
ans.append(nums2[i])
hash[nums2[i]] -= 1
return ans