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 ... 阅读详情

一.问题描述

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

二.解题思路

注意到这道题要求的时间复杂度是O(log(m+n)),如果说是O(n),那很简单一次遍历排个序就有了,主要难的就是log(m+n)的时间复杂度。看到log,这题肯定是要用二分法的,说实话想了挺久还是没想出来,后面借鉴了别人的思路

原思路是用英文写的(建议先去看下英文概述的图,再来看我讲的规律会好点),我简单概述一下核心和注意的点,后面会放别人想法的链接

别人的想法

我们直接想,假设我们的中位数是在A[i],会有什么样的规律可循。

可以知道中位数左边的数都小于它,右边的数都大于它,并且各占一半(假设数组长度和是偶数)

这就意味着A数组从A[0]到A[i-1],B数组从B[0]到B[j-1]都要小于A[i]

i和j有什么关系,我们知道中位数两边个数相等

这说明 i+j=(m+n)/2

j就可以用i来表示

其实就相当于我们现在要找的是从数组A的某个位置切一刀,这一刀把AB两个数组分成了两个模块

我们用二分搜索来找这一刀的位置

假设切的位置A是在i,B是在j

i=(imin+imax)/2

只要满足A[i]>A[j-1] and A[i-1]<A[j],那么这就到了正确的划分,这样我们只需要比较

A[i]和A[j]里选小的那个,A[i-1],A[j-1]里选大的那个(假设数组长度和是偶数,奇数的话也很容易)

这两个数就是中位数,

如果不满足A[i]>A[j-1],说明A[i]小了,让i增大就行了,这时候更新左边界

imin=i+1,搜索右边那一半

如果不满足A[i-1]<A[j],说明A[i-1]太大了,更新右边界

imax=i-1

这就是主要的思路,其实这道题主要的难点是,如何处理边界

i=0,=lenA,j=0,=lenA

的时候,怎么处理找那两个中位数

然后提供一个如果数组长度是奇数的时候的处理方法:

我是让j=(lenA+lenB)/2

因为/会取整丢弃小数位,这样子使得当数组长度和为奇数的时候,左部分会少一位(数组B的0~j是左部分),这样就可以保证如果数组长度和数奇数的话,中位数就是右边部分的最小值

同时数组B长度一定得大于数组A,不然j可能会是负数

这道题主要难点就是二分的方法和边界的处理,特别是左部分最大值和右部分的最小值在边界的时候应该怎么找

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        lenA=len(nums1)
        lenB=len(nums2)
        if lenA>lenB:
            nums1,nums2,lenA,lenB=nums2,nums1,lenB,lenA
        imin,imax=0,lenA,
        mid=int((lenA+lenB)/2)
        while imin<=imax:
            i=int((imin+imax)/2)
            j=mid-i
            if i<lenA and nums1[i]<nums2[j-1]:
                imin=i+1
            elif 0<i and nums1[i-1]>nums2[j]:
                imax=i-1
            else:
                if lenA == 0:
                    if (lenA + lenB) % 2 == 0:
                        return (nums2[int(lenB / 2)] + nums2[int(lenB / 2) - 1]) / 2
                    else:
                        return nums2[int(lenB / 2)]
                min_right,max_left=0,0
                if i==0:max_left=nums2[j-1]
                elif j==0:max_left=nums1[i-1]
                else: max_left=max(nums1[i-1],nums2[j-1])

                if i==lenA:min_right=nums2[j]
                elif j==lenB:min_right=nums1[i]
                else:min_right=min(nums1[i],nums2[j])
                if (lenA+lenB)%2==0:
                    return (max_left+min_right)/2
                else:
                    return min_right

 

【UG/NX二次开发】记录在二次开发中遇到的坑 阅读详情

相关推荐

知识图谱_知识图谱 | 知识图谱做用户画像

导读:最近一直在思考怎么用知识图谱做推荐,但是目前能知道的内容都是基于路径的推荐和基于图特征的推荐,所以能不能换一个角度,探究一下用知识图谱怎么做用户画像,因为画像也是推荐系统重要的一部分。现在的知识图谱+推荐怎么做的传统的用户画像怎么做现在的知识图谱+推荐怎么做的?基于路径:可以理解成基于图谱的多路径召回,或者多路径推荐,然后根据路径的转移概率进行排序从而达到推荐的效果,基于路径比较适合简单的推...

weixin_28801659的博客 1473

【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

[CARLA系列--01]CARLA 0.9.15 在Windows下的安装教程(一)

Carla是一款开源的自动驾驶仿真器,它基本可以用来帮助训练自动驾驶的所有模块,包括感知系统,Localization, 规划系统等等.Carla这个产品目前已经更新到了最新的0.9.15版本,目前遇到好多人在windows系统上如何安装可编辑版的Carla遇到了好多问题,所以针对在windows上的安装,推出此列教程.

汽车ECU自动化测试 4661

【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

Matlab:常见涡旋光束仿真

代码: clc clear all close all %% 环形涡旋光束 N = 200; lambda = 632e-9; %波长为632nm k = 2*pi/lambda; %波数 w0 = 3; %束腰半径 x = linspace(-10,10,N); y = linspace(-10,10,N); [X,Y] = meshgrid(x,y); [t...

zzz997的博客 3万+

P450酶催化循环的Amber-Gromacs混合模拟实战:从血红素加氧到产物释放

本文详细介绍了针对P450酶完整催化循环的Amber-Gromacs混合模拟实战策略。通过Amber为关键氧合血红素中间体(CPDI)构建精确力场,再利用Gromacs的高效GPU加速进行长时间尺度动力学模拟,完整覆盖从底物结合到产物释放的催化过程,为研究酶催化机制提供了强大的计算工具。

weixin_29201859的博客 322

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的博客 1431

如何在Android上使用OpenCV进行摄像头标定

如何在Android上使用OpenCV进行摄像头标定,我们这里使用官方一个例程,其实并不难,只是网上的资料少了而已。相机标定是计算机视觉工作的前提,为了确定相机矩阵和畸变参数。

花草的博客 3448

【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

在 Windows 上安装 OpenCV – C++ / Python

而且,安装并不是一件容易的事。这些安装程序仅适用于安装 OpenCV for C++。如果您想安装适用于 Python 的 OpenCV,您将在博客后面找到相关信息。在这篇博文中,我们将在 Windows 上安装适用于 C++ 和 Python 的 OpenCV。C++ 安装是在自定义安装 exe 文件的帮助下完成的。而Python的安装是通过Anaconda完成的。从源代码安装 OpenCV 需要花费大量时间。根据您的硬件和安装配置,该过程可能需要 5 分钟到 2 小时不等。

Demondai999的博客 2098

多组学联合分析揭示CHAMP1调控肌母细胞融合的表观遗传机制

表观遗传调控是理解细胞命运决定的关键,而多组学联合分析则提供了从基因表达到染色质状态再到三维互作的全景视角。ATAC-seq可检测染色质开放性,Cut&Tag能定位增强子活性标记,HiCAR则捕捉增强子-启动子间的远程互作。通过整合转录组与这些表观数据,可系统解析基因调控的分子机制。在肌肉发育研究中,借助该策略发现CHAMP1通过影响肌源性增强子活性与染色质环稳定性,调控肌母细胞融合。这项研究展示了多组学证据链闭环如何将新因子功能与具体表型联系起来,为类似课题设计与数据整合提供了可复制的范式。

weixin_33423874的博客 229

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

仿真学习系列(四十九):Sigrity仿真之电容库制作

在高速电路设计中,电源完整性(PI)是确保系统稳定、可靠运行的关键因素。随着电子产品对性能的要求不断提升,PDN(电源分配网络)的设计与优化变得尤为重要。为了确保电源网络在高速工作状态下不会引发电压波动和信号干扰,我们需要在设计中精确地选择电容器进行优化,而电容库的制作则是这一过程的核心。 OptimizePI作为一个强大的电源完整性优化工具,能够帮助设计师根据不同的目标,批量进行PDN仿真,以得出最佳电容选择。

案例文章,高速信号 232

【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

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Leetcode->array分类1.Two Sum 4. Median of Two Sorted Arrays 11. Container With Most Water 15. 3sum

1.two sum Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. 首先想两个for循环遍历,排除掉。 既然‘you may not use the same element twice’,用过的num就不在选择范围里 ...

王大胖的博客 274

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

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

[LeetCode]4. Median of Two Sorted Arrays

每天一道编程题题目描述样例python解法C语言解法 题目描述 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...

xingyu97的博客 147

leetcode4 Median of Two Sorted Arrays

给出两个有序的数组,求其中位数,元素个数位偶数个,则求其上中位数和下中位数的平均数. 最简单粗暴的做法就是直接从两个数组的开头对比,建立两个指针遍历数组,时间为O(n+m).(数组1长度为n数组2长度为m) 如果想要log的时间复杂度就得使用二分了,如果是计算其中位数,序列中必然有(m+n)/2个数小于中位数mid,我们就根据这个公式就可以进行二分,我们先取数组1的中位数mid1,数组1中有n

京东放养的爬虫 1113

Leetcode 4. Median of Two Sorted Arrays (python+cpp)

题目 解法1:双指针 版本一:time complexity O(m+n),space complexity O(m+n) class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); int p1 = 0, p2 =

qq_37821701的博客 248

LeetCode 4. Median of Two Sorted Arrays

LeetCode 4. Median of Two Sorted Arrays 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 time

My Blog 182

4. Median of Two Sorted Arrays

快一个月没有更新了,但是题目还是在写的,分析都直接写在了leetcode自带编辑器了 我给自己定的春节假期是2月4号之前,虽然现在假期大大大的延长,还是要按照自己的节奏来,所以在2月4成功写到了400道,还是挺累的……之后一个星期没有写 写到350道的时候题号差不多就到了700,想想之前很多题目都跳过了,又回去对前面跳过的简单难度和中等难度查漏补缺了一番,写到了400。 在11月开始重新上刷题的时...

qq_42024783的博客 143

LeetCode 4: 寻找两个有序数组的中位数(Median of Two Sorted Arrays)解法汇总

文章目录我的解法C++ 我的C++代码同步更新在我的Github 我的解法 这是一道很简单的两个有序向量的二路归并问题。直接上代码。 C++ class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { double re...

Utopiabuntu的博客 324

leetcode 第4题 Median of Two Sorted Arrays

算法分析: 对题目要求在已经排序好的两个数组之中寻找中位数,nums1的数组长度为m,nums2的数组长度为n,要求复杂度为O(log(m+n))例如: 输入:nums1 = [1, 3], nums2 = [2] 输出:2.0 输入:nums1 = [1, 2], nums2 = [3, 4] 输出:2.5 题目本身并不复杂,用传统的思维方法,一层循环就可以解决,但难点在于复杂度为O

qq_23156731的博客 227

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的专栏 744

leetcode刷题day03-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 (m+n)). You may assume nums1 and nums2 ca.

qq_22473333的博客 159

Median of Two Sorted Arrays - 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 assume nums1 and num...

nullptr的博客 138

LeetCode 题解(66): 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 complexity should be O(log (m+n)). 题解: 找 m + n 个数的中位数,若 m + n 为偶

546
上一篇: leetcode 3. Longest Substring Without Repeating Characters(无重复最长子串) 解法 python
下一篇: leetcode 1038. Binary Search Tree to Greater Sum Tree 解法 python
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值