Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
注意:如果为input:[1],[1,1],需要判断hashmap[num] > 0
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
#hashmap的index为nums的值,value为值出现的个数
hashmap = {}
result = []
for num in nums1:
if num in hashmap:
hashmap[num] += 1
else:
hashmap[num] = 1
for num in nums2:
if num in hashmap and hashmap[num] > 0:
result.append(num)
hashmap[num] -= 1
return result
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = []
hashmap=collections.Counter(nums1)
for num in nums2:
if num in hashmap and hashmap[num] > 0:
hashmap[num] -= 1
result.append(num)
return result