来自北大算法课的Leetcode题解:349. 两个数组的交集

代码仓库Github | Leetcode solutions @doubleZ0108 from Peking University.

  • 解法1(T60% S83%):直接调用库函数的set() 首先将两个数组通过集合去重,然后通过intersection()取两个集合的交集,最后转换为列表返回
  • 解法2(T60% S46%):双指针。首先将两数组排序,然后双指针分别指向两数组的开始,如果当前指针指向数字和结果的最后一位一样则循环跳过这些位(注意防止数组越界),然后判断两指针指向,如果相等则添加到结果中,否则让指向数字小的指针往后移动一位
class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1.sort()
        nums2.sort()
        i, j = 0, 0
        res = []
        while i<len(nums1) and j<len(nums2):
            if len(res) > 0:
                while i<len(nums1) and nums1[i]==res[-1]: i += 1
                while j<len(nums2) and nums2[j]==res[-1]: j += 1

            if i>=len(nums1) or j>=len(nums2): break
            
            if nums1[i]==nums2[j]:
                res.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] < nums2[j]: i += 1
            else: j += 1

        return res

    def otherSolution(self, nums1, nums2):
        s1, s2 = set(nums1), set(nums2)
        return list(s1.intersection(s2))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

doubleZ0108

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值