4. Median of Two Sorted Arrays(归并排序思想)

LeetCode4 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)). Java AC版本 立即下载

原题

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

题目分析

这道题目在Leetcode上属于难度hard级别。

这里写图片描述

此题的基本思想可以借鉴归并排序。

第一步,先对两个有序列归并排序,不同的是当进行到一半时,便可终止归并,得到 i 和 j 分别指向两个有序数组此时的位置。

第二步,如果两个数组的总个数为奇数,则返回 i 和 j 所指向的元素的更大者即可;

若为偶数,需要利用 i 和 j 所指向的元素大小进行讨论。

  • 若 i 所指向的元素更大,则循环中最后的遍历落在了 nums1 中,那么,如果 i−1>=0 (即 i 前存在前一个元素)且nums1[i−1]>=nums2[j] ,则中位数为 (nums1[i−1]+nums1[i])/2.0 ;
  • 如果 i−1==0 或者 nums1[i−1]<nums2[j] ,则中位数为 (nums1[i]+nums2[j])/2.0 ;若落在了 nums2 中,则对称地进行讨论。

需要注意的是边界情况,例如 nums1=1,nums2=kong 。

代码实现C#

    public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
            int n1 = nums1.Length, n2 = nums2.Length, i = 0, j = 0;

            // sorting nums1 and nums2, sum pointer
            int sumpointer = 0; 
            for (i = 0, j = 0; (i < n1 || j < n2) && sumpointer <= (n1 + n2) >> 1; sumpointer++){
            //indicates nums1.Length<nums2.Length          
                if (i >= n1) j++;     
                //nums1.Length>nums2.Length                        
                else if (j >= n2) i++;
                //combination nums1 and nums2 to sort
                else if (nums1[i] <= nums2[j]) i++; 
                else j++;
            }

            bool even = (n1 + n2) % 2 == 0;
            --i; --j;
            if (i < 0) return even == true ? (nums2[j - 1] + nums2[j]) / 2.0 : nums2[j];
            if (j < 0) return even == true ? (nums1[i - 1] + nums1[i]) / 2.0 : nums1[i];

            //odd analysis
            if (!even) return Math.Max(nums1[i], nums2[j]);

            //even analysis
            //shows stone point is in nums2
            if (nums1[i] < nums2[j]){ 
                if (j - 1 >= 0 && nums1[i] <= nums2[j - 1])
                    return (nums2[j - 1] + nums2[j]) / 2.0;
                return (nums1[i] + nums2[j]) / 2.0;
            }
            // shows stone point is in nums1
            if (i - 1 >= 0 && nums2[j] <= nums1[i - 1])
                return (nums1[i - 1] + nums1[i]) / 2.0;
            return (nums1[i] + nums2[j]) / 2.0;

    }

代码实现python

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        n1 = len(nums1)
        n2 = len(nums2)
        i = 0
        j = 0
        # sorting nums1 and nums2, sum pointer
        sumpointer = 0
        while (i < n1 or j < n2) and sumpointer <= (n1 + n2) >> 1:
            if i >= n1:
                j+=1
            elif j >= n2:
                i+=1
            # combination nums1 and nums2 to sort
            elif nums1[i] <= nums2[j]:
                i+=1
            else:
                j+=1
            sumpointer+=1
        even = (n1 + n2) % 2 == 0
        i-=1
        j-=1
        if i < 0:
            return (nums2[j - 1] + nums2[j]) / 2.0 if even == True  else nums2[j]
        if j < 0:
            return (nums1[i - 1] + nums1[i]) / 2.0 if even == True else nums1[i]
        # odd analysis
        if even==False:
            return max(nums1[i], nums2[j])
        #even analysis, 1.shows stone point is in nums2
        if nums1[i] < nums2[j]:
            if j - 1 >= 0 and nums1[i] <= nums2[j - 1]:
                return (nums2[j - 1] + nums2[j]) / 2.0
            return (nums1[i] + nums2[j]) / 2.0
        # shows stone point is in nums1
        if i - 1 >= 0 and nums2[j] <= nums1[i - 1]:
                return (nums1[i - 1] + nums1[i]) / 2.0
        return (nums1[i] + nums2[j]) / 2.0

结果分析:
时间复杂度为 O(0.5(m+n)) ,空间复杂度为 O(1) ,计算结果排名:

这里写图片描述

以下是我之前写的一篇归并排序博客,地址,在此一块汇总到这里。
http://blog.csdn.net/daigualu/article/details/68491601

归并排序

归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列。

排序过程

归并排序的算法我们通常用递归实现,先把待排序区间[start,end]以中点二分,接着把左边子区间排序,再把右边子区间排序,这是分解的过程。最后把左区间和右区间用一次归并操作合并成有序的区间[start,end],这是治理的过程。如何归并呢? 简单来说两个指针分别指向待归并的数组,选出较小的,放到第三个指针控制的临时数组中。

实现代码

主题框架代码如下,见代码注释。

         /// <summary>
        /// 主题框架
        /// </summary>
        private void divideMerge(int[] unsort, int start, int end, int[] sort)
        {
            if (start < end)
            {
                int middle = (start + end) >> 1;
                //对前半部分归并排序
                divideMerge(unsort, start, middle, sort); 
                //对后半部分归并排序
                divideMerge(unsort, middle + 1, end, sort); 
                //此时,前、后半部分已经是有序序列,对它们实行二路归并
                merge(unsort, start, middle, end, sort);
            }

        }

调用的二路归并方法merge的实现代码如下,要特别注意临界值,此处pe为最大索引值,而不是元素个数,注意此处。

        /// <summary>
        /// 合并算法
        /// </summary>
        /// <param name="unsort">无序数组</param>
        /// <param name="ps">第1部分的起始位置</param>
        /// <param name="pm">第1部分的结束位置</param>
        /// <param name="pe">第2部分的结束位置</param>
        /// <param name="sort"></param>
        private void merge(int[] unsort, int ps, int pm, int pe, int[] sort)
        {
            int i = ps; //第一部分的取值范围为[ps,pm]
            int j = pm+1; //第二部分的取值范围为[pm+1,pe]

            int sortCount = 0;

            while (i <= pm && j <= pe)
            {
                if (unsort[i] < unsort[j])
                    sort[sortCount++] = unsort[i++];
                else
                    sort[sortCount++] = unsort[j++];
            }

            while (i <= pm)
                sort[sortCount++] = unsort[i++];

            while (j <= pe)
                sort[sortCount++] = unsort[j++];

            for (int sortIndex = 0; sortIndex < sortCount; sortIndex++)
                unsort[ps + sortIndex] = sort[sortIndex];

        }

封装了一个排序类,见下,提供的API有2个,

  1. 归并排序接口MergeSort()
  2. 构造函数,构造无序数组
    public class CMergeSort
    {
        private int[] _unsortArray;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="unsortArray"></param>
        public CMergeSort(int[] unsortArray)
        {
            _unsortArray = unsortArray;
        }

        /// <summary>
        /// 归并排序接口
        /// </summary>
        /// <returns></returns>
        public int[] MergeSort()
        {
            int maxIndex = _unsortArray.GetUpperBound(0);
            int[] sort = new int[maxIndex + 1];
            divideMerge(_unsortArray, 0, maxIndex, sort);
            return sort;
        }
  }

客户端调用

客户端调用刚才写好的对象,对无序数组a实行归并排序。

        static void Main(string[] args)
        {
            int[] a = new int[] { 9,7,10,6,3,5,2,7,9};
            var merge = new CMergeSort(a);
            int[] sortArray = merge.MergeSort();

            Console.Read();
        }

记录了归并排序的过程,对此进行了结果分析。

结果分析

对数组的{ 9,7,10,6,3,5,2,7,9}的归并排序过程如下,


这里写图片描述

归并排序过程的前半部分,过程示意图见下,从图中可见,步骤1,2,3,4一直分割区间,等到步骤5时,左右区间长度都为1,此时发生一次归并,结果再与另一个区间长度为1的归并,即步骤6;步骤7分割,步骤8归并,步骤9归并后前半部分合并结束;
后半部分过程与前半部分归并一致,不再详述。

这里写图片描述

源码下载

http://download.csdn.net/detail/daigualu/9799598

我做Leetcode的专栏

http://blog.csdn.net/column/details/14761.html

汇总在GitHub上

地址,欢迎一起讨论!若有问题请联系我!
https://github.com/jackzhenguo/leetcode-csharp

树莓派5新手必看:保姆级ibus中文输入法安装与配置全流程(含.bashrc设置避坑) 本文详细介绍了在树莓派5上安装和配置ibus中文输入法的完整流程,包括系统环境准备、ibus框架安装、图形界面配置及常见问题解决方案。通过清晰的步骤说明和避坑指南,帮助新手快速实现中文输入功能,提升开发效率。 阅读详情

相关推荐

ANSYS HFSS从入门到放弃?这些隐藏技巧让3D电磁仿真效率翻倍

本文针对已掌握ANSYS HFSS基础操作但受困于仿真效率的用户,深入剖析了提升3D电磁仿真速度的核心技巧。文章重点介绍了如何精准控制自适应网格剖分、合理配置GPU加速与分布式计算以释放硬件潜能,并分享了针对PCB/封装仿真的HFSS 3D Layout优化工作流。掌握这些方法,能有效将仿真时间从“天”级缩短至“小时”级,大幅提升天线、高速连接器等复杂电磁结构的设计迭代效率。

weixin_29046611的博客 435

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

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

czp_374的博客 531

S型速度曲线C程序实现

S型速度曲线C语言程序实现 前言 S型曲线相较于梯形速度曲线具有运行更加平稳的特点,S型曲线共有八种运行情况,感兴趣可以查阅相关文献 代码段 #include <stdio.h> #include <math.h> #define FP64 double int main(void) { /**************************** 定义相关变量(需要映射到PLC寄存器才能进行监控) ***********************/ FP6

LSX312441548的博客 8406

4. Median of Two Sorted Arrays

ProblemThere 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 =

Bryan要加油 464

StarCCM+ 导入STL几何模型进行仿真

通过 Import Surface Mesh 的方法导入 STL 文件进行仿真

薛定谔的alpha狗 6138

手把手教你用P-MOS管搭建双电源自动切换电路(含AO3401选型指南)

本文提供了一份基于P-MOS管AO3401构建高可靠双电源自动切换电路的实战指南。文章详细对比了继电器、理想二极管与MOS管方案的优劣,深入解析了AO3401的关键参数选型,并手把手指导了从原理图设计、PCB布局到上电调试的全过程,旨在帮助硬件工程师和创客以极低成本实现无缝、高效的电源冗余方案。

moss5的博客 1271

LeetCode——Median of Two Sorted Arrays

看到这个题,坑定有很多东西都忘记了吧!没事!进来就行了,你不会的差不多我也不会,我都有解释清楚,进来吧!一块成长进步! 哈哈!做完了,第一次得到那么高的评价! 一下子高兴过头了,回头来发现自己还是那么差 其实还是挺难的,我看半天都没看懂

Blackoutdragon的博客 605

小白快速上手 labelme:新手图像标注详解教程

本教程旨在帮助初次接触 labelme 的用户快速上手该软件,掌握基本操作与标注流程,为语义分割数据集做准备。

小白一枚~ 2万+

【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

【AI大模型:前沿】44、大模型+机器人:从自动化工具到通用智能体的技术革命与应用全景

大模型与机器人的融合催生了“具身智能体”,突破传统机器人智能化缺失、功能单一等瓶颈。大模型赋予机器人三大能力:常识推理(如热牛奶需去包装)、模糊指令解析(如“整理书桌”拆解步骤)、零样本任务泛化(如搭乐高桥)。技术实现上,通过多模态融合(视觉-语言-动作)、仿真训练(虚拟试错)和实时反馈(动态调整动作)形成闭环。主流框架如Google RT-2(端到端动作生成)、斯坦福Q-Transformer(强化学习优化)和Figure 01(ChatGPT驱动人形机器人)各具优势,可适配工业、家庭等场景。该技术正重塑

2025博客之星Top81。专注AI工程化与架构实战。从分布式思维到模型部署,用工程化视角为你厘清AI落地的真实路径。 2032

2026年江苏省职业院校技能大赛高职组“软件测试”赛项智能体辅助测试参考答案

2026年江苏省职业院校技能大赛高职组“软件测试”赛项智能体辅助测试参考答案

我是网络安全兼技能大赛工程师,专注网络安全技术学习与技能大赛实战!持续分享最新的技术文章,帮你少走弯路,一起在技术赛道上进步~ 1404

Leetcode 4 Median of Two Sorted Arrays

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

思维决定一切 3万+

威纶通触摸屏与S7-1200以太网通信的具体方法和步骤(非常详细)

威纶通触摸屏与S7-1200以太网通信的具体方法和步骤(非常详细)

Robot_PLC_HMI_Automation 1万+

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

孑辞的博客 413

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Median of Two Sorted Arrays

题目要求是求出两个已排序的数组的中位数,如果两个数组的总的个数为偶数,则返回中间两个数字的平均数。 思路: 解题思路就是根据归并排序的思想,利用归并排序中合并两个已排序数组的方法。声明count变量,在两个数组中没选出一个数的时候,count++,直到count等于中位数所在的位置即可。以下是代码过程: 1. 极端情况,两个数字都为空,返回-1; 2. 根据两个数组的size()确定中位数

Artwoo_GIS的博客 674

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

LeetCode 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)).思路分析:这题容易想到O(m+n)的解法,就是先Merge两个数组,然后返

Coding for Dreams 1734

Leetcode 4. Median of Two Sorted Arrays

Leetcode 4.Median of Two Sorted Arrays Given two sorted arraysnums1andnums2of sizemandnrespectively, returnthe medianof the two sorted arrays. 找两个已经有序数组合起来中的中位数 两个有序数组,很容易想到归并排序,用归并的思想这道题也很好做,两个数组分别需要扫描一次,时间效率为O(m+n)。 这道题难点在于如何达到要求的O(log(m...

tracygirlhhh的博客 224

LeetCode 4. Median of Two Sorted Arrays 寻找两个有序数组的中位数 C#

前言 本文介绍了 LeetCode 第 4 题 , “Median of Two Sorted Arrays”, 也就是 “寻找两个有序数组的中位数” 的问题. 本文使用 C# 语言完成题目,介绍了多种方法供大家参考。 题目 English LeetCode 4. Median of Two Sorted Arrays There are two sorted arrays nums1 and n...

wf824284257的博客 941

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)). 思路 要求出两个有序数组(长度分别为

buptlrw的专栏 745

[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 complexity should be O(log (m+n)). You may assume n...

Learning from the mistakes 264

Leetcode004-Median of Two Sorted Arrays

Leetcode004-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 comple

Flora_xuan1993 527

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)). You may assume nums1 and n...

小猪爱拱地 640

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

题目 <https://leetcode.com/problems/median-of-two-sorted-arrays> 题意 给出两个有序的数组,找出这两个数组所有数的中位数。 Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The...

weixin_33894992的博客 193

LeetCode4 寻找两个有序数组的中位数 Median of Two Sorted Arrays

LeetCode4 寻找两个有序数组的中位数 Median of Two Sorted Arrays 题目描述 题目地址:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/ 题目难度:困难 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(lo...

沙码龙 391

LeetCode系列:4 Median of Two Sorted Arrays

Q: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 n...

SuAdrenine的博客 221

LeetCode解法java:4. Median of Two Sorted Arrays

思路:这个题需要求中位数,有两个思路:1.直接将两个数组放到一个数组里排序2.因为两个数组是有序数组,所以用归并排序的思路对数组进行处理,也可以达到给数组排序的效果,但是时间复杂度能达到O(log (m+n))思路1:的代码,直接调用java本身给出的api,将两个数组放到一个长度为两个数组之和的数组里,然后将数组排序,取中间的一个或两个数的平均数,返回就可以了,时间复杂度O(nlogn)。pub...

wangdatiancai的博客 242
上一篇: 2. Add Two Numbers
下一篇: leetcode已完成题目索引
zg1g
博客等级 码龄16年 1993粉丝 839原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值