leetcode 350. Intersection of Two Arrays II 详解 python3

一.问题描述

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

二.解题思路

题目要求找两个数组的交集,其实就是类似找两个集合的交集,只不过数组的交集里可能有重复元素出现。

就原本这道题,解法就是用hashmap记录nums1和nums2中每个数字出现的次数。

然后遍历nums1(或者nums2):

判断当前这个key在不在另外一个数组里,在的话说明有交集,加n个key在结果中,n为key在两个数组中出现次数较少的次数。

时间复杂度: O(N),空间复杂度:O(N)。

这个问题主要是探讨一下后面的follow up:

1.如果是有序数组怎么优化。

假如是升序。

如果是有序数组的话就很简单了,不用做hashmap,一边遍历一边处理。

用两个指针指向当前两个数组的遍历点, index1,index2.

<1. 如果 nums1[index1]=nums2[index2],将nums1[index1]加入结果,两个指针都+1,

<2. 如果nums1[index1]>nums2[index2],index2指针+1

<3.如果nums2[index1]<nums2[index2],index1指针+1

时间复杂度O(m+n), m和n分别是nums1和nums2的长度, 空间复杂度就是存放的结果:O(k),k是最后的结果长度。最大就是m+n,当两个数组一模一样的时候。

2.如果nums1的长度小于nums2,哪个算法好?

如果nums1的长度远小于nums2,那么遍历nums1,找到该元素在右边有序数组的边界(左边和右边,可以用二分法来做, Find First and Last Position of Element in Sorted Array),时间复杂度是O(nlongm),因为n远小于m,所以可能复杂度要比O(m+n)要小。

3.如果内存有限,不能一次性加载所有元素怎么办?

emmm,就用指针一次读一个元素出来,老老实实在一里面找吧。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束

三.源码

#version 1
from collections import Counter
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        if not nums1 or not nums2: return []
        num2cnt1,res=Counter(nums1),[]
        for num in nums2 :
            if num in num2cnt1 and num2cnt1[num]>0:
                res.append(num)
                num2cnt1[num]-=1
        return res

#version 2
from collections import Counter
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        if not nums1 or not nums2: return []
        num2cnt1,num2cnt2=Counter(nums1),Counter(nums2)
        res=[]
        for key in num2cnt1:
            if key in num2cnt2:
                res.extend([key]*min(num2cnt1[key],num2cnt2[key]))
        return res

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值