zoukankan      html  css  js  c++  java
  • leetcode-easy-array-50. Intersection of Two Arrays II

    mycode  77.78%

    class Solution(object):
        def intersect(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            def deal(dic,nums):
                res = []
                for item in nums:
                    if item in dic and dic[item]!=0:
                        res.append(item)
                        dic[item] -= 1
                return res
            
            dic = {}
            if len(nums1) > len(nums2): 
                for item in nums2:
                    dic[item] = dic.get(item,0) + 1
                return deal(dic,nums1)
            else:
                for item in nums1:
                    dic[item] = dic.get(item,0) + 1
                return deal(dic,nums2)

    参考:

    1、应用collection.Counter库,可以实现与运算

    class Solution(object):
        def intersect(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            return list((collections.Counter(nums1) & collections.Counter(nums2)).elements())

     2、 

    class Solution(object):
        def intersect(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            res = []
            map = {}
            for i in nums1:
                map[i] = map[i]+1 if i in map else 1
            for j in nums2:
                if j in map and map[j] > 0:
                    res.append(j)
                    map[j] -= 1
    
            return res
  • 相关阅读:
    Hive UDF 用户自定义函数 编程及使用
    Hive 常用命令和语句
    Hive 配置显示表头和数据库信息
    Hive 安装配置
    Hadoop完全分布式集群环境搭建
    Java 文件切割工具类
    MongoDB 安装配置
    NodeJS 安装配置
    Java 截屏工具类
    Maven 配置本地依赖jar
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10985062.html
Copyright © 2011-2022 走看看