【LeetCode 4】Median of Two Sorted Arrays(Python)

[ LeetCode ] 4. Median of Two Sorted Arrays (C++ & Python) 题目:4. Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log ... 阅读详情

Problem:

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

You may assume nums1 and nums2 cannot be both empty.

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

Solutions:

solution1:

     这个算法虽然在网站上通过了,但是算法复杂度并不是O(log(m+n)),而是O(m+n),且算法实现复杂。

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        cache = []
        len_nums1 = len(nums1)
        len_nums2 = len(nums2)
        mid_idx = []
        total_len = len_nums1+len_nums2
        if total_len%2==0:
            mix_idx.extend([int(total_len/2)-1,int(total_len/2)])
        else:
            mid_idx.append(int(total_len/2))
        i1,i2=0,0
        for i in range(mid_idx[0]+1):
            if i1>=len_nums1:
                cache.append(nums2[i2+mid_idx[0]-i-1])
                if len(mix_idx)==2:
                    cache.append(nums2[i2+mid_idx[1]-i-1])
                break
            elif i2>=len_nums2:
                cache.append(nums1[i1+mid_idx[0]-i-1])
                if len(mix_idx)==2:
                    cache.append(nums1[i1+mid_idx[1]-i-1])
                break
            else:
                if nums1[i1]>=nums2[i2]:
                    i2+=1
                    if i==mid_idx[0]:
                        cache.append(nums2[i2-1])
                        if len(mid_idx)==2:
                            cache.append(min(nums1[i1],nums2[i2]))
                        break
                else:
                    i1+=1
                    if i==mid_idx[0]:
                        cache.append(nums1[i1-1])
                        if len(mid_idx)==2:
                            cache.append(min(nums1[i1],nums2[i2]))
                        break
        return sum(cache)/len(cache)

solution2:

       这个算法参考算法导论中讲述的二分法的思想,算法复杂度为O(log(m+n)),较难想到,但非常巧妙

class Solution(object):
    def get_kth_num(self, nums1, nums2, k):
        len1 = len(nums1)
        len2 = len(nums2)
        if len1>len2:
            return self.get_kth_num(nums2,nums1,k)
        if len(nums1)==0:
            return nums2[k-1]
        elif k==1:
            return min(nums1[0],nums2[0])
        else:
            pa = min(len1, int(k/2))
            pb = k - pa
            if nums1[pa-1]>nums2[pb-1]:
                return self.get_kth_num(nums1,nums2[pb:],pa)
            else:
                return self.get_kth_num(nums1[pa:],nums2,pb)
            
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        len1 = len(nums1)
        len2 = len(nums2)
        k = int((len1+len2)/2)
        if k==0 or (len1+len2)!=2*k:
            return self.get_kth_num(nums1, nums2, k+1)
        else:
            return (self.get_kth_num(nums1, nums2, k) + self.get_kth_num(nums1, nums2, k+1))*0.5

solution 3:

      第三种解决方法为leetcode官方给出的解决方案,官方还提供了完整的分析思路,可自行查阅参考

def median(A, B):
    m, n = len(A), len(B)
    if m > n:
        A, B, m, n = B, A, n, m
    if n == 0:
        raise ValueError

    imin, imax, half_len = 0, m, (m + n + 1) / 2
    while imin <= imax:
        i = (imin + imax) / 2
        j = half_len - i
        if i < m and B[j-1] > A[i]:
            # i is too small, must increase it
            imin = i + 1
        elif i > 0 and A[i-1] > B[j]:
            # i is too big, must decrease it
            imax = i - 1
        else:
            # i is perfect

            if i == 0: max_of_left = B[j-1]
            elif j == 0: max_of_left = A[i-1]
            else: max_of_left = max(A[i-1], B[j-1])

            if (m + n) % 2 == 1:
                return max_of_left

            if i == m: min_of_right = B[j]
            elif j == n: min_of_right = A[i]
            else: min_of_right = min(A[i], B[j])

            return (max_of_left + min_of_right) / 2.0

 

GPU架构(1.1)--介绍 GPU的 VPU(Vision Processing Unit)架构 基于自研的 VPU(Vision Processing Unit)架构,专为高性能图形处理和深度学习设计。VPU 架构通过优化计算单元、内存层次结构、同步机制和指令流水线,提供了卓越的性能和能效。VPU 架构通过优化计算单元、内存层次结构、同步机制和指令流水线,提供了卓越的性能和能效。这种架构不仅适用于高性能图形处理,还广泛应用于深度学习、科学计算和边缘计算等领域。通过了解 VPU 架构的详细设计和工作原理,读者可以更好地利用这些先进的 GPU 技术,开发出高效、可靠的计算系统。 阅读详情

相关推荐

从FOC到你的无人机:深入浅出讲透Clark/Park变换在无刷电机控制中的核心作用

本文深入解析Clark变换与Park变换在无刷电机控制中的核心作用,揭示其如何将三相交流电转换为旋转坐标系下的直流量,实现无人机电机的高效精准控制。通过STM32硬件加速和工程实践案例,展示这对数学变换如何成为FOC算法的神经中枢,大幅提升系统响应速度和能效表现。

weixin_42628941的博客 175

【leetcode-Python】- 二分搜索 - 4. Median of Two Sorted Arrays

题目链接 4. Median of Two Sorted Arrays 题目描述 给定两个非降序数组nums1和nums2,大小分别为m和n,返回两个数组合并后的中位数。要求时间复杂度为O(log(m+n)). 示例 输入:nums1 = [1,3],nums2 = [2] 输出:2.00000 输入:nums1 = [1,2],nums2 = [3,4] 输出:2.50000 输入:nums1= [],nums2 = [1] 输出:1.0000 解决思路一 插一句题外话

gulaixiangjuejue的博客 647

Cocos Creator3.5.2使用Spine切换皮肤

3、然后获取当前spine中是否有皮肤数据,如果spine连皮肤数据都没有,接着写可能会error,这里的 skins[skin],是判断皮肤列表中是否有需要更换的皮肤。2、因为spine往往意味着异步加载,换肤时也经常出现频繁异步的情况,所以下一步我们要可以判断当前spine组件里是否已经加载好了spine文件。换肤前隐藏好需要换肤的节点,避免穿帮;官网文档的换肤流程太简化,对于实际使用来说会有各种各样的问题。1、首先获取对应的spine组件。这里的skin自然是外部传入的需要换肤的皮肤名。

tc654321的博客 1828

【python】【leetcode】【算法题目4—Median of Two Sorted Arrays】

一、题目描述 题目原文: There are two sorted arraysnums1andnums2of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

一只奋斗的小虫的博客 533

RC电路(一):微分|积分

的取值不同,会导致输出波形和输入波形之间的关系也不同,由此也会产生不同的应用。输出为0,随着电容充满电,运放-输入端得到的分压为正最大值,可等效成一个电压源,且电压不可突变,此时电流反向为最大值,开始充电时的容抗为0,电压不可突变则电压差为0,运放。开始充电时的容抗为0,电压不可突变则电压差为0,运放。输入端得到的分压也不可突变,随着电容放完电,于是。,因电容上电压不能突变(来不及充电,相当于短路,由上分析可得积分运算电路中,输出为运放的负最大峰值,随着电容充满电,输出为运放的正最大峰值,随着电容放完电,

既有随处可栖的江湖,也有追风逐梦的骁勇! 1万+

端到端自动驾驶的精准测试场景开发

1. 背景介绍 自动驾驶技术的发展正在改变交通运输的未来,然而,要实现安全可靠的自动驾驶,需要进行大量的测试和验证。端到端自动驾驶系统的测试场景开发是实现这一目标的关键。本文将详细介绍端到端自动驾驶的精准测试场景开发,包括核心概念、算法原理、数学模型、项目实践,以及未来发展趋势。 2. 核心概念与联系

AGI×大数据,开启智能时代的认知跃迁;解码AGI,赋能数据驱动的智能革命。 1322

LeetCode in Python 4. Median of Two Sorted Arrays (寻找两个正序数组的中位数)

重复直至找到一个合适的m1使得从两个数组中取出的元素为合并两数组后最小的half个元素。4)对于数组奇偶元素个数的分开判断,如果数组有奇数个元素,则中位数应该是取完half(此half为向下取的整数)后两个数组右中位数的最小值,举例说明,有13个元素,half=6,中位数应为两数组合并后第7个元素,而第7个元素来源只能是取完half个数后两数组的右中位数中的一个,即right1和right2中的一个,根据正序排列的顺序,小的在前大的在后,故第7个元素应为min(right1, right2)。

m0_45175452的博客 1432

5 分钟上手 Kimi Work:安装、配置、跑通第一个任务

这篇文章提供了Kimi Work的快速入门指南,帮助用户在5分钟内完成从安装到运行第一个任务的全过程。主要内容包括: 安装步骤: macOS用户下载.dmg文件并拖入Applications Windows用户下载.exe安装包,需注意中文路径问题 初始设置: 使用现有Kimi账号登录 检查任务配额和文件访问权限 首个任务推荐: 建议从简单的本地文件整理开始(如按类型分类桌面文件) 详细说明了任务执行流程和审批机制 常见问题: 计划生成卡顿的解决方法 文件无变化的排查步骤 进阶建议: 提供难度递增的后续任务

sg_knight的专栏 2870

[LeeCode] 4. Median of Two Sorted Arrays (Python)

4.Median of Two Sorted Arrays Hard There are two sorted arraysnums1andnums2of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assumenums1andnums2cannot be bot...

热爱编程,热爱技术 242

Android SystemUI——初始化流程(三)

1、Android 系统在启动之后,首先会Zygote进程,Zygote进程又会进一步启动 SystemServer进程,它会启动各种系统所需要的服务,在监听AMS启动完毕之后,还会启动SystemUIService。2、在启动SystemUIService服务之前,系统首先会创建SystemUI对应的进程,获取SystemUIAppComponentFactory实例对象,调用instantiateApplicationCompat创建SystemUIApplication实例对象并设置回调方法。

小旭的专栏 1175

论文深度解析:基于大语言模型的城市公园多维度感知解码与公平性提升

本文针对城市公园感知测量的精细化不足与公平性评估缺口,提出了一套融合社交媒体数据与大语言模型(LLM)的创新分析框架。通过领域适配微调开发的Park-Perception-LLM模型,实现了对感知可达性、可用性、吸引力三大核心维度83%-91%的高精度分类。将该感知指标创新性地融入增强两步浮动集水区法(E2SFCA),以香港高密度城市为案例,系统揭示了公园质量与数量的空间不平等及错配模式。借助多元回归模型,深入挖掘了公园内部特征、宏观建成环境、微观街道景观及时间因素对感知的影响机制。

May the Force be with you 1027

Leetcode4答案与解析 - Median of Two Sorted Arrays(python)

原题 Leetcode原题传送门 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may...

liubai01的博客 526

【读代码】SQLBot:开源自然语言转SQL智能助手原理与实践

SQLBot是 DataEase 团队开源的自然语言转 SQL 智能助手,致力于让非技术用户也能通过自然语言与数据库对话,自动生成 SQL 查询,实现自助数据分析、智能BI问答、报表生成等场景。SQLBot 结合了大语言模型(LLM)、数据库元数据解析、SQL解析与执行等多项技术,具备强大的多数据库适配能力和灵活的扩展性。降低数据分析门槛,让业务人员无需掌握SQL即可获取数据洞察支持多种数据库类型,适应企业多样化数据环境提供可扩展的API和插件机制,便于集成到各类BI、数据平台和业务系统。

kakaZhui的博客 832

【LeetCode】4. Median of Two Sorted Arrays(Python)

Problem 有两个排序的数组nums1和nums2分别为m和n。 找到两个排序数组的中位数。总运行时间复杂度应为O(log(m + n))。 您可以假设nums1和nums2 不能都为空。 例1: nums1 = [1,3] nums2 = [2] 中位数是2.0 例2: nums1 = [1,2] nums2 = [3,4] 中位数为(2 + 3)/ 2 = 2.5 Algorithmi...

E.W的博客 890

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

leetcode 4. Median of Two Sorted Arrays 解法 python

一.问题描述 There are two sorted arraysnums1andnums2of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assumenum...

CSerwangjun的博客 1545

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

LeetCode 4. Median of Two Sorted Arrays Python3

LeetCode 4. Median of Two Sorted Arrays Python3 Description 点击查看题目 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run t...

与你的博客 419

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

[LeetCode] 4. Median of Two Sorted Arrays(Python)

[LeetCode] 4. Median of Two Sorted Arrays(Python)1. 题目2. 题目理解3. 代码实现 1. 题目 Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1:

qq_35029666的博客 933

leetcode 4. Median of Two Sorted Arrays的思路与python实现

思路 基本只能靠背。边缘条件太恶心了... 代码 class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: m, n = len(nums1), len(nums2) if m > n: # 上面的要小一点...

qq_35175413的博客 299

LeetCode 4.Median of Two Sorted Arrays (Python)

4. Median of Two Sorted Arrays(Python)两个排序数组的中位数

iwanthn的博客 515

Leetcode 4.Median of Two Sorted Arrays with Python

class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ m = len...

dxcve的博客 172

LeetCode:4. Median of Two Sorted Arrays - Python

问题描述: 4. 寻找两个有序数组的中位数 给定两个大小为m和n的有序数组nums1和nums2。 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为O(log(m + n))。 你可以假设nums1和nums2不会同时为空。 示例 1: nums1 = [1, 3] nums2 = [2] 则中位数是 2.0 示例 2: nums1 = [1, 2] nums2 = [3, 4] ...

Growth Diary 2696

4.Median of Two Sorted Arrays Leetcode Python

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 这题的一种O(m+n)的解法是mergesort的一步,依次比较两

hyperbolechi的专栏 745

【LeetCode】4. Median of Two Sorted Arrays解题报告(Python)

参考博客 测试代码: class Solution: def getKth(self, A, B, k): k = int(k) lenA = len(A); lenB = len(B) if lenA &amp;amp;amp;gt; lenB: return self.getKth(B, A, k) if lenA == 0: r...

L141210113的专栏 1217

【LeetCode】4. Median of Two Sorted Arrays 解题报告(Python)

【LeetCode】4. Median of Two Sorted Arrays 解题报告(Python)题目描述解法:类二分查找 题目地址:https://leetcode.com/problems/median-of-two-sorted-arrays/ 题目描述 There are two sorted arrays nums1 and nums2 of size m and n respe...

ttinch的博客 226

LeetCode 4 — Median of Two Sorted Arrays (C++ Java Python)

题目:http://oj.leetcode.com/problems/median-of-two-sorted-arrays/ There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time comple

龙之梦 6496

LeetCode4. Median of Two Sorted Arrays(C++/Python)

There are two sorted arraysnums1andnums2of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assumenums1andn...

qq_41562704的博客 217
上一篇: spark基础知识汇总
下一篇: 【LeetCode 385】Mini Parser(Python)
思维之上
博客等级 码龄11年 15粉丝 31原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值