美文网首页
[easy][Array][two-pointer][hasht

[easy][Array][two-pointer][hasht

作者: 小双2510 | 来源:发表于2017-11-27 12:41 被阅读0次

原题:

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

相关文章

网友评论

      本文标题:[easy][Array][two-pointer][hasht

      本文链接:https://www.haomeiwen.com/subject/iuorbxtx.html