LeetCode:350. 两个数组的交集 II(python,JavaScript)

350. 两个数组的交集 II


在这里插入图片描述

python

法1:出现相同后,将列表中出现的删除。

在这里插入图片描述

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res = []
        if len(nums1)<len(nums2):
            nums1,nums2 = nums2,nums1
        for i in range(len(nums2)):
            if nums2[i] in nums1:
                del nums1[nums1.index(nums2[i])]
                res.append(nums2[i])
        return res

法2:使用哈希表(每次重复,就加入结果,并且value值-1)

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        dic,res = {},[]
        if len(nums1)<len(nums2):
            nums1,nums2 = nums2,nums1
        for n in nums1:
            if n in dic:
                dic[n] += 1
            else:
                dic[n] = 1
        for n in nums2:
            if n in dic:
                if dic[n] != 0:
                    res.append(n)
                    dic[n] -= 1
        return res

法3:如果给定数组是排好序的,使用双指针法

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        #如果给定数组排好序
        nums1.sort()
        nums2.sort()
        i,j,res = 0,0,[]
        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                res.append(nums1[i])
                i,j = i+1,j+1
            elif nums1[i]>nums2[j]:
                j += 1
            else:
                i += 1
        return res

javaScript

排序+双指针

var intersect = function(nums1, nums2) {
    nums1.sort((a,b) => a-b);
    nums2.sort((a,b) => a-b);
    let i=0,j=0,res = []
    while(i<nums1.length && j <nums2.length){
        if(nums1[i] == nums2[j]){
            res.push(nums1[i])
            i++;j++
        }else if(nums1[i] < nums2[j]) i++;
        else j++
    }
    return res
};
  • 13
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南岸青栀*

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

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

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

打赏作者

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

抵扣说明:

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

余额充值