350. Intersection of Two Arrays II -- 双指针、哈希表、排序、二分搜索

350. Intersection of Two Arrays II

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

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

解1:双指针,并把结果添加到栈中。

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1.sort()
        nums2.sort()
        p1 = 0
        p2 = 0
        ans = []
        while (p1 < len(nums1)) and (p2 < len(nums2)):
            if nums1[p1] == nums2[p2]:
                ans.append(nums1[p1])
                p1 += 1
                p2 += 1

            elif nums1[p1] < nums2[p2]:
                p1 += 1
            else:
                p2 += 1
        return ans

解2:
哈希表,首先把nums1的字符添加到哈希表中,然后遍历nums2,找到一个nums1中有的数并且计数大于0,就添加到放回的列表中,并且计数减去1.

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """

        ans = []
        d = {}
        for num in nums1:
            d[num] = d[num] + 1 if num in d else 1
        for j in nums2:
            if j in d and d[j] > 0:
                ans.append(j)
                d[j] -= 1
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值