首页 > 其他分享 >leetcode 350. Intersection of Two Arrays II

leetcode 350. Intersection of Two Arrays II

时间:2023-05-30 17:35:18浏览次数:48  
标签:Arrays Counter List Two II int num nums1 nums2

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

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

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?

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        # use sort, or set(Counter)
        ans = []
        cnt = collections.Counter(nums1)
        for n in nums2:
            if n in cnt and cnt[n] > 0:
                cnt[n] -= 1
                ans.append(n)
        return ans

可以更精简些:

from collections import Counter

class Solution(object):
    def intersect(self, nums1, nums2):
        c1, c2 = Counter(nums1), Counter(nums2)
        return sum([[num] * min(c1[num], c2[num]) for num in c1 & c2], [])

自己写的话:

class Solution(object):
    def intersect(self, nums1, nums2):

        counts = {}
        res = []

        for num in nums1:
            counts[num] = counts.get(num, 0) + 1

        for num in nums2:
            if num in counts and counts[num] > 0:
                res.append(num)
                counts[num] -= 1

        return res

 

注意:

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        # use sort, or set(Counter)
        return list(set(nums1) & set(nums2))是不可以的,因为set里是没有重复数据的:
Input: [1,2,2,1] [2,2]
Output: [2]
Expected: [2,2]

另外就是使用sort,归并思路:

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        # use sort, or set(Counter)
        nums1.sort()
        nums2.sort()
        i = j = 0
        ans = []
        l1, l2 = len(nums1), len(nums2)
        while i < l1 and j < l2:
            if nums1[i] == nums2[j]:
                ans.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1
        return ans

 还有使用binsearch来避免归并思路的。

标签:Arrays,Counter,List,Two,II,int,num,nums1,nums2
From: https://blog.51cto.com/u_11908275/6381006

相关文章

  • leetcode 231. Power of Two
    Givenaninteger,writeafunctiontodetermineifitisapoweroftwo.classSolution(object):defisPowerOfTwo(self,n):""":typen:int:rtype:bool"""#-4???ifn>......
  • CF1398E Two Types of Spells 题解 set
    题目链接:https://codeforces.com/problemset/problem/1398/E题目大意你有一个集合,初始为空。有两种类型的元素,一种是普通元素,一种是强化元素,两种元素都有一个数值。有\(n\)次操作,每次操作会往集合中加入一个元素或者删除一个元素。每次操作后,你都需要确定集合中元素的一个......
  • Wallys/Qualcomm network chip/ipq9574/ipq9554/wireless connectivity solutions.
     QualcommWi-Fi7networkchipsolutionsIPQ9574andIPQ9554areadvancedwirelessconnectivitysolutionsdevelopedbyQualcommTechnologies.ThesechipsaredesignedtosupporttheWi-Fi7(802.11be)standard,whichofferssignificantimprovementsinspe......
  • #yyds干货盘点# LeetCode程序员面试金典:填充每个节点的下一个右侧节点指针 II
    题目:给定一个二叉树:structNode{ intval; Node*left; Node*right; Node*next;}填充它的每个next指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将next指针设置为NULL。初始状态下,所有 next指针都被设置为NULL。 示例1:输入:root=[1,2,3......
  • [CVPR23 Highlight] Side Adapter Network for Open-Vocabulary Semantic Segmentatio
    **摘要本文提出了一个用于开放词汇语义分割的新框架SAN,将语义分割任务建模为区域识别问题,提取maskproposals并使用CLIP对mask进行识别。SAN可以重新利用CLIP的特征,因此其本身可以非常轻量;同时网络可以端到端地进行训练,从而使SAN适应冻结的CLIP模型。本文方法需要很少的参数量,且......
  • 文献阅读-Inferring Networks of Diffusion and Influence
    Authors: ManuelGomez-Rodriguez, JureLeskovec, AndreasKrause AuthorsInfo&ClaimsACMTransactionsonKnowledgeDiscoveryfromDataVolume5Issue4ArticleNo.:21pp1–37https://doi.org/10.1145/2086737.2086741  Abstract......
  • 518.零钱兑换II
    给你一个整数数组coins表示不同面额的硬币,另给一个整数amount表示总金额。请你计算并返回可以凑成总金额的硬币组合数。如果任何硬币组合都无法凑出总金额,返回0。假设每一种面额的硬币有无限个。题目数据保证结果符合32位带符号整数。输入:amount=5,coins=[1,2,......
  • git团队协作_network
    Git教程:https://www.runoob.com/git/git-tutorial.htmlGit大全:Git大全-Gitee.comGit分支管理一种适合小团队的Git协作流程-知乎(zhihu.com)[GitHub的Fork是什么意思?-知乎(zhihu.com)](https://www.zhihu.com/question/20431718/answer/74250205?utm_campaign=s......
  • 剑指 Offer II 039. 直方图最大矩形面积
    题目链接:剑指OfferII039.直方图最大矩形面积方法:单调栈解题思路以直方图中的某一条为高的最大(面积)矩形的宽度为\(r-l+1\),其中\(r\)表示在其右边第一个小于(或等于)当前高度的下标,\(l\)表示在其左边第一个小于当前高度下标。\(l\),\(r\)可以利用单调栈在\(O(1)......
  • linphone-NetworkManger.java文件分析
    功能InterceptnetworkstatechangesandupdatelinphonecorethroughLinphoneManger翻译拦截网络状态的变化,并通过LinphoneManger更新linphone核心内容。NetworkManager.java/**......