原題
計算兩個數組的交
注意事項
每個元素出現次數得和在數組里一樣答案可以以任意順序給出
樣例
nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
解題思路
- 遍歷第一個數組,構建hash map,計數
- 遍歷第二個數組,如果存在在hash map而且個數大于零,加入res數組
- 其他方法:先排序,兩根指針
完整代碼
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
map = {}
for x in nums1:
if x not in map:
map[x] = 1
else:
map[x] += 1
res = []
for y in nums2:
if y in map and map[y] > 0:
res.append(y)
map[y] -= 1
return res