[easy][Array][two-pointer][hashtable]349.Intersection of Two Arrays

原题:

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:
Each element in the result must be unique.
The result can be in any order.

思路是:

参见350.

代码是:

class Solution:
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        dicts = {}
        res = []
        
        for i,num in enumerate(nums1):
            if num not in dicts:
                dicts[num] = 1
            else:
                dicts[num] += 1
            
        for j,num in enumerate(nums2):
            if num in dicts:
                res.append(num)
                del dicts[num]
        
        return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。