LeetCode 350 [Intersection of Two Array II]

原題

計算兩個數組的交
注意事項
每個元素出現次數得和在數組里一樣答案可以以任意順序給出

樣例
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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容