[Leetcode] 4. Median of Two Sorted Arrays 解题报告

图解LeetCode4:Median of Two Sorted Arrays 文章目录理解题意思路1:最直观解法思路2:二分查找代码实现结论 Leetcode算法系列将详细讲解一些经典的面试算法题。 今天的算法是LeetCode中第四个题目,Median of Two Sorted Arrays,也就是给定两个有序数组求出中位数。   理解题意 首先给定的是两个有序数组,比如{1,3}以及{2},那么合并这两个数组就是{1,2,3},因此很显然中位数是2; 再给定... 阅读详情

题目

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)).

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

思路

找出中位数其实可以泛化为求两个数组中第k大的数,此时求中位数只是其中的一个特例而已。首先看看两种平凡情况:

1)k == 1:此时只需要返回nums1和nums2的首元素的最小值即可;

2)如果nums1或者nums2为空,则直接返回另一数组中的第k个元素即可。

如果不属于平凡情况,则递归处理:分别计算nums1和nums2的第k/2个数,并比较两者的大小。如果nums1的第k/2个数小于nums2的第k/2个数,那么结果不可能出现在nums1中的前k/2个数中;此时可以减掉nums1中的前k/2个数,并进入下一次递归;如果nums1的第k/2个数大于nums2中的第k/2个数,那么结果不可能出现在nums2中的前k/2个数中,此时可以减掉nums2中的前k/2个数,并进入下一次递归。

注意在该例中k是以1为起始索引的,所以要注意转换。


代码

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int total_length = nums1.size() + nums2.size();
        if(total_length % 2 != 0)       // odd case
            return findKth(nums1, nums2, 0, 0, total_length / 2 + 1);
        else                            // even case
            return (findKth(nums1, nums2, 0, 0, total_length / 2) +
                    findKth(nums1, nums2, 0, 0, total_length / 2 + 1)) / 2.0;
    }
private:
    double findKth(vector<int>& nums1,  vector<int>& nums2, int s1, int s2, int k)
    {
        if(s1 >= nums1.size())
            return nums2[s2 + k - 1];
        if(s2 >= nums2.size())
            return nums1[s1 + k - 1];
        if(k == 1)
            return min(nums1[s1], nums2[s2]);
        int nums1_key = s1 + k / 2 - 1 >= nums1.size() ? INT_MAX : nums1[s1 + k / 2 - 1];
        int nums2_key = s2 + k / 2 - 1 >= nums2.size() ? INT_MAX : nums2[s2 + k / 2 - 1];
        if(nums1_key < nums2_key)       // drop the first half of nums1
            return findKth(nums1, nums2, s1 + k / 2, s2, k - k / 2);
        else                            // drop the first half of nums2
            return findKth(nums1, nums2, s1, s2 + k / 2, k - k / 2);
    }
};


【力扣Leetcode题解系列之0004. Median of Two Sorted Arrays:寻找两个正序数组的中位数解题攻略】 本文介绍了力扣算法题"Median of Two Sorted Arrays"的解题方法。给定两个正序数组,要求在O(log(m+n))时间复杂度内找到它们的中位数。核心思路是使用二分查找,通过合理划分两个数组的位置,使得左半部分元素都小于右半部分。文章提供了C++和Go两种语言的实现代码,并分析算法的时间复杂度为O(log(m+n)),空间复杂度为O(1)。该解法充分利用二分查找的高效性,是解决这类问题的经典方法。 阅读详情

相关推荐

Zynq-PS-SDK(12) 之 VDMA+VTC+AXI4S-VideoOut 视频通路硬件搭建

前面分别叙述了《Zynq-PS-SDK(9) 之 VDMA》、《Zynq-PS-SDK(10) 之 VTC》以及《Zynq-PS-SDK(11) 之 AXI4-Stream To Video Out》;搭建一个简单的视频通路(Framebuffer -> HDMI)就要用到这些个模块,总体的设计框图如下所示: 视频数据的 Framebuffer 在 DDR 中,通过 Processing System 写入进去; 数据通过高带宽的 AXI4 接口(这里用到了 HP AXI,即 64bits 带

StephenZhou 5589

LeetCode 4 Median of Two Sorted Arrays 解题报告

原文链接: http://hankerzheng.com/blog/LeetCode-Median-of-Two-Sorted-ArraysProblem DescriptionLeetCode 4 Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively

hanzheng992的博客 435

Linux yum源配置以及yum命令讲解

前面为大家介绍了RPM二进制包安装软件,RPM包安装的最大的缺点也提到过,就是依赖性太强,一旦遇到依赖问题,则需要我们手动解决包之间具有依赖性的问题,今天为大家介绍一种可自动解决包之间依赖关系的安装方式:yum。 yum 全称“Yellow dog Updater, Modified”,是一个专门为了解决包的依赖关系而存在的软件包管理器。就好像 Windows 系统上我们通常可以通过各种软件管家实现软件的一键安装、升级和卸载,yum就是Linux 系统中的一键安装工具。yum 解决依赖关系的基本逻辑是:yu

九派Linux的博客 2282

【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的专栏 1215

OpenBCI脑电数据处理实战:用MNE库从Raw对象到可视化分析全流程

本文提供了使用MNE-Python库处理OpenBCI脑电数据的完整实战指南。从通过BrainFlow库获取原始数据流、创建核心的Raw对象,到进行工频滤波、带通滤波等关键预处理步骤,最后实现时域信号、功率谱密度及地形图等多种专业可视化分析,手把手教你完成脑机接口数据处理的全流程。

gin88的博客 367

海康威视摄像机SDK二次开发--提取音频保存至文件

由于最近在开发海康威视摄像头,特此记录一下如何提取音频数据,这里主要依靠语音对讲返回的音频数据,通过回调函数写入文件中,加个WAV头即可播放,编码格式可以自己设置在代码中有注释 文件结构 其中CameraInfo内容可以参看海康威视摄像机SDK二次开发–实时预览视频流保存到指定文件中 HIKSDKSaveRealData中的内容 package ClientDemo; import ClientDemo.CameraInfo; import com.sun.jna.NativeLong; import

RichardoMu的博客 3172

[leetcode] 4. Median of Two Sorted Arrays 解题报告

题目链接: https://leetcode.com/problems/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

小榕流光的专栏 836

立创开源4G+GPS定位系统:基于微信小程序的低成本低功耗追踪方案

本文介绍了一个基于立创开源平台的超小型4G+GPS定位系统方案。该方案采用28mm*28mm主板,集成4G Cat.1通信与GPS定位,通过微信小程序“点灯专家”实现远程追踪管理,具备低成本、低功耗、易于部署的特点,适用于电动车、宠物、资产追踪等多种场景。

weixin_28895791的博客 393

Leetcode解题报告: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)). 难度:Hard 解题

wengyunpeng的博客 557

window下迁移SVN仓库到新的windows服务器

window下迁移SVN仓库到新的windows服务器

Bertram的博客 4690

RT-DETR的AIF模块+YOLOv8:融合注意力与特征交互,打造实时检测的科研级进阶方案

从理解AIF模块“细粒度注意力+跨尺度交互”的核心设计,到亲手将其嵌入YOLOv8并验证在复杂场景的表现,再到基于此探索属于自己的科研与工程方向——这个过程能让你深刻理解“注意力机制与CNN融合”在实时检测中的核心价值。现在就开始行动,相信你会在实时目标检测的“智能进化”之路上,走出一条属于自己的技术路径。从实验对比图可见,集成AIF模块的YOLOv8,其mAP(平均精度)在多个阈值下均有提升,尤其是mAP50-95(高IoU阈值下的精度)提升更为显著,充分证明了AIF对细粒度特征的捕捉能力。

m0_64661770的博客 186

【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的博客 224

【YOLOv8全方位学习手册】第四章 数据增强:从扩充数据到塑造模型的认知边界

"""使用 Albumentations 做自定义增强,兼容 YOLO 格式"""])# 转成 numpy# boxes 必须是 [[x_min,y_min,x_max,y_max], ...]# 在数据加载时调用你可以把集成到 PyTorch 的 Dataset 类里,或使用 Ultralytics 自带的DataLoader。

VectorShift的博客 211

4. Median of Two Sorted Arrays - Hard - Leetcode解题报告

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...

weixin_34185560的博客 114

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

LeetCode(4) Median of Two Sorted Arrays解题报告

求两个有序数组的中位数 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))

jackllvv的博客 265

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

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

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

郝春雨的博客 259

Leetcode (4) Median of Two Sorted Arrays 解题报告

题目:Median of Two Sorted Arrays 找到两排序数组的全部元素的中位数。

晨星的博客 278

Leetcode 4 Median of Two Sorted Arrays

今天发现了leetcode上面一道题,觉得非常经典,记录之。 题目是这样的:给定两个已经排序好的数组(可能为空),找到两者所有元素中第k大的元素。另外一种更加具体的形式是,找到所有元素的中位数。本篇文章我们只讨论更加一般性的问题:如何找到两个数组中第k大的元素?不过,测试是用的两个数组的中位数的题目,Leetcode第4题 Median of Two Sorted Arrays 方案1:假

思维决定一切 3万+

Leetcode 4 median-of-two-sorted-arrays题解

Leetcode median-of-two-sorted-arrays题解 虽然很简单,但是值得纪念一下,第一次超过100%的人 题目链接 思路: **Talking is no use, show your my codes** 代码: class Solution { public double findMedianSortedArrays(int[] nums1, int[] n...

qq_42308861的博客 318

Median of Two Sorted Arrays

题目:leetcode 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 sh

bupt8846的专栏 808

LeetCode 4. Median of Two Sorted Arrays题解

题目 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...

孑辞的博客 411

[LeetCode]Median of Two Sorted Array

[LeetCode]Median of Two Sorted Array

xmb24的博客 338

【LeetCode】解题4:Median of Two Sorted Arrays

LeetCode解题 4:Median of Two Sorted Arrays Problem 4: Median of Two Sorted Arrays [Hard]解题思路Solution (Java)修改过程 Problem 4: Median of Two Sorted Arrays [Hard] There are two sorted arrays nums1 and nums2 ...

Fayedily的博客 331

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

LeetCode4. Median of Two Sorted Arrays

之前没钻研过LeetCode,上次做题时,以为要找什么类型的题目就在搜索栏输入对应的关键词,结果输入divide-and-conquer才搜到一题,后来经提醒才知道在网页右侧有个提供各种关键词的topics框部,点击了divide-and-conquer便搜到了好多道相关题目,方便许多。之前真是太蠢了。 这次选择的是第4题:Median of Two Sorted Arrays  难度系数为H

reborncgy的博客 355

LeetCode 4. Median of Two Sorted Arrays 题解

本题是二分查找的经典问题,主要考察对二分查找算法的理解和应用。通过将问题转化为在两个有序数组中找到第 k 小的元素,我们可以使用二分查找来高效地解决这个问题。二分查找的核心思想是:使用两个指针分别指向查找区间的两端,计算中间位置,比较中间元素与目标值的大小,根据比较结果缩小查找区间,直到找到目标值或确定目标值不存在。这种方法的时间复杂度为 O(log(min(m, n))),适用于大规模有序数组的中位数查找。掌握二分查找的原理,对于理解搜索算法和算法设计思想非常重要。

cannonjinx的博客 1008
上一篇: [Leetcode] 3. Longest Substring without Repeating Characters 解题报告
下一篇: [Leetcode] 5. Longest Palindromic Substring 解题报告
魔豆Magicbean
博客等级 码龄19年 146粉丝 742原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值