LeetCode: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; 再给定... 阅读详情

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

我的解决方案,就是重新将数组A/B重新排序,然后获取中间值。

     public  double FindMedianSortedArrays(int[] nums1, int[] nums2)
        {
            int num1_length = nums1.Length;
            int num2_length = nums2.Length;
            int maxlength = num1_length > num2_length ? num1_length : num2_length;
            int[] newnums = new int[num1_length + num2_length];
            int target_length = 0;
            if (maxlength == 0) return 0.00d;
         
            for (int i = 0; i < maxlength; i++)
            {
                if (num1_length ==0|| num2_length ==0|| nums1[0] <= nums2[0]|| nums1[0] <= nums2[num2_length - 1])
                {
                    handleArray(ref nums1, ref newnums, ref target_length, i);
                    handleArray(ref nums2, ref newnums, ref target_length, i);
                }
                else
                {
                    handleArray(ref nums2, ref newnums, ref target_length, i);
                    handleArray(ref nums1, ref newnums, ref target_length, i);
                }
            }
            if (target_length % 2==0)
            {
                return Math.Round((Convert.ToDouble(newnums[target_length / 2 - 1] + newnums[target_length / 2]) / 2),2);
            }
            else
            {
                return Convert.ToDouble(newnums[target_length / 2]);
            }
        }

时间复杂度为O(m+n),显然还是不行。

Solution in LeetCode

Approach 1: Recursive Approach

 

 

要解决问题,首先我们得清楚了解median的含义

分成两块相同大小的块,而且其中一块大于另外一块。(如下图A,B)

如把A,B分别切分为相等的两块

left_A | right_A

A[0], A[1], ..., A[i-1] | A[i], A[i+1], ..., A[m-1]


left_B | right_B

B[0], B[1], ..., B[j-1] | B[j], B[j+1], ..., B[n-1]

假设A块的大小为m,B块的大小为n,那我们就可以得出

\text{len}(\text{left\_A}) = i, \text{len}(\text{right\_A}) = m - ilen(left_A)=i,len(right_A)=m−i.

当i=0时,left_A为空;当i=m时,right_A为空。

同理,B块也是一样。

如果以下两个条件成立

  1. \text{len}(\text{left\_part}) = \text{len}(\text{right\_part})len(left_part)=len(right_part)

  2. \max(\text{left\_part}) \leq \min(\text{right\_part})max(left_part)≤min(right_part)

那么可以得出

 

接下来,我们逐一分析两个数组之间的情况,如果数组A,B如例子所示,那么就满足以下两个条件:

如A={2,3} B={1,4},i=(0+2)/2=1,j=(2+2+1)/2-1=1,B[0]=1<=A[1]=2 A[0]=2<=B[1]=4

这个时候,你会想问"为什么n必须大于等于m"?因为这样j的索引项出超出范围了。如A={2,3} B={4},i=1,j=1,那么b[1]就是出界了。

接下来,我们就按照[0,m]的范围i~j一直循环下去:

  1. 令imin=0,imax=m, 范围就是[0,m]

  2. 令i=(imin+imax)/2,j=(m+n+1)/2-i

  3. 我们接下来遇到以下三种情况:

    - B[j−1]≤A[i] and \text{A}[i-1] \leq \text{B}[j]A[i−1]≤B[j] ,也就是说我们已经找到目标i了。

    - B[j−1]>A[i] ,意味着A块可能很小,我们需要增加i,去看一下B[j−1]>A[i] 

    - A[i−1]>B[j],意味着B块可能很小,我们需要减少i,再看看A[i−1]>B[j]

  4. 如果i找到了,那么就可以返回结果了

          当m+n是偶数时,需要左边的Max_Left和右边的Min_Left的平均值。

         当m+n是奇数时,只需要拿左边的Max_Left即可,因为Median就在块中。

 

接下来,我需要考虑下特殊情况,如i=0/j=0/i=m/j=n的情况。

  • 当i=0时,也就是说A_Left为空,直接可以得出Max_Left=B[j-1]

  • 当j=0时,也就是说B_Left为空,直接可以得出Max_Right=A[i-1]

  • 当i=m时,也就是说A_Right为空,直接可以得出Max_Right=B[j]

  • 当j=n时,也就是说B_Right为空,直接可以得出Max_Right=A[i]

算法如下:

   public double FindMedianSortedArrays(int[] A, int[] B)
            {
                int m = A.Length;
                int n = B.Length;
                if (m > n)
                { // to ensure m<=n
                    int[] temp = A; A = B; B = temp;
                    int tmp = m; m = n; n = tmp;
                }
                int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2;
                while (iMin <= iMax)
                {
                    int i = (iMin + iMax) / 2;
                    int j = halfLen - i;
                    if (i < iMax && B[j - 1] > A[i])
                    {
                        iMin = i + 1; // i is too small
                    }
                    else if (i > iMin && A[i - 1] > B[j])
                    {
                        iMax = i - 1; // i is too big
                    }
                     else
                    { // i is perfect
                        int maxLeft = 0;
                        if (i == 0) { maxLeft = B[j - 1]; }
                        else if (j == 0) { maxLeft = A[i - 1]; }
                        else { maxLeft = Math.Max(A[i - 1], B[j - 1]); }
                        if ((m + n) % 2 == 1) { return maxLeft; }

                        int minRight = 0;
                        if (i == m) { minRight = B[j]; }
                        else if (j == n) { minRight = A[i]; }
                        else { minRight = Math.Min(B[j], A[i]); }

                        return (maxLeft + minRight) / 2.0;
                    }
                }
                return 0.0;
            }

 

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

相关推荐

LeetCode - #4 求两个有序数组的中间值

前言 我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。微博:@故胤道长)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 LeetCode 算法到目前我们已经更新了 3 期,我们会保持更新时间和进度(周一、周三、周五早上 9:00 发布),每期的内容不多,我们希望大家可以在上班路上阅读,长久积累会有很大提升。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。 难度

记录从移动端、鸿蒙到物联网与AI的完整实战与思考。专注于分享可复用的工程方案与产品思维,尤其深入鸿蒙生态与全栈开发。以十年工程与管理沉淀,为你提供清晰的技术纵深路径。坚信技术的价值在于“贯通”与“落地”。 1039

算法题连击-寻找两个有序数组的中位数

题目 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 请你找出这两个有序数组的中位数。 你可以假设 nums1 和 nums2 不会同时为空。 示例 1: nums1 = [1, 3] nums2 = [2] 则中位数是 2.0 示例 2: nums1 = [1, 2] nums2 = [3, 4] 则中位数是 (2 + 3)/2 = 2.5 解题 执行用时: 276 m...

Wion Wan 209

Ansys Zemax与Speos协同设计:HUD系统从光学优化到驾驶视觉验证全流程解析

本文详细解析了如何利用Ansys Zemax与Speos协同工作流,完成HUD系统从光学内核优化到驾驶视觉验证的全流程。通过Zemax进行精密光学设计与像差校正,再通过Speos进行HOA定量分析和虚拟驾驶舱仿真,实现了数据无损流转与验证闭环,有效解决了光学性能与视觉感知脱节的核心问题,显著提升HUD设计效率与可靠性。

git9versioner的博客 530

两个有序数组的中间值(Median of Two Sorted Arrays)__By leetCode

Example nums1 = [1, 3] nums2 = [2] The median is 2.0 nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 求两个有序数组的中间值 One public double findMedianSortedArrays(int[] a, int...

huisiwarmhome的博客 977

深度排查:网讯网卡WX1860AL4千兆网口降速百兆的硬件陷阱

本文详细剖析了网讯网卡WX1860AL4千兆网口降速至百兆的硬件故障排查过程。通过分析千兆以太网硬件原理,提供从网线、供电到PCB走线、焊接残留的标准化检修流程,并分享两种典型硬件陷阱(线序错误与焊锡短路)的实战修复案例,为硬件工程师解决类似传输速率问题提供系统性的诊断思路与方法。

a3b4c5的博客 1111

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)). Example 1: nums1 =

相信相信的力量 3193

微信小程序 实现拼图功能

微信小程序 实现碎片拼图

weixin_45689786的博客 2250

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

内核工作FAST‘25 Artifact Evaluation流程记录

在我们的paper中,复现需要用到傲腾持久化内存,因此,需要AE Reviewer访问到内网服务器中。我们的思路是购买云服务器,将其作为跳板机,内网服务器通过SSH反向代理与公网服务器建立隧道,AE Reviewer通过隧道访问内网服务器。我们在AE过程中使用。然后,把一切复现需要的代码环境,在chroot里面配置完成。

不定期更新系统使用、编程小技巧,哔哩哔哩账号:https://space.bilibili.com/399455629,欢迎关注 1215

顶会新宠!Gate+Attention创新思路发A会

性能提升:在Places2自然场景和CelebA-HQ人脸数据集上,与以往方法相比,该系统在自由形式掩码修复任务中取得了更高的质量和更低的误差(例如,平均ℓ1误差和ℓ2误差显著降低)。硬件效率提升:Griffin和Hawk在TPU-v3上的训练效率与Transformer相当,且在推理时具有更低的延迟和显著更高的吞吐量。门控卷积:提出了一种新的门控卷积机制,通过学习每个通道在每个空间位置的动态特征选择机制,解决了传统卷积将所有输入像素视为有效像素的问题。

2501_92785035的博客 975

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

YOLOv13改进策略【小目标改进】| Shape-NWD:融合改进,结合Shape-IoU和NWD 更好地适应小目标特性

Bw−wgt2h−hgt2weight2Bweight2w−wgt​2h−hgt​2​其中weight2weight = 2weight2。

Limiiiing的博客 587

[LeetCode]Median of Two Sorted Array

[LeetCode]Median of Two Sorted Array

xmb24的博客 338

顶级AI大模型白嫖ChatGPT Plus1个月,0成本薅顶配功能

Chat*** Plus限时免费1个月!原价20美元/月的顶配功能

BUG猿的博客 7283

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Leetcode 4 Median of Two Sorted Arrays

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

思维决定一切 3万+

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

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

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

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

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 should be O(log (m+n)). 题目示例: Example 1:

漫漫学习路 2949

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

孑辞的博客 412

leetcode之 median of two sorted arrays

这是我做的第二个leetcode题目,一开始以为和第一个一样很简单,但是做的过程中才发现这个题目非常难,给人一种“刚上战场就踩上地雷挂掉了”的感觉。后来搜了一下leetcode的难度分布表(leetcode难度及面试频率)才发现,该问题是难度为5的问题,真是小看了它!网上搜了很多答案,但是鲜见简明正确的解答,唯有一种寻找第k小值的方法非常好,在此整理一下。        首先对leetcode的

姚光超的专栏 9万+

LeetCode每天刷day4:Median of Two Sorted Arrays

题目链接:Median of Two Sorted Arrays C++: class Solution { public: double findMedianSortedArrays(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) { int len1 = nums1.size(); ...

Jos's blogs 168

【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)). 有两个排序的数组A和B分别是m和n。找到两个排序数...

码农印象 2292

Median of Two Sorted Arrays - LeetCode

目录 题目链接 注意点 解法 小结 题目链接 Median of Two Sorted Arrays - LeetCode 注意点 要考虑数组长度不一致的情况 解法 解法一:将两个数组合并成一个有序数组,根据数组长度分奇偶情况求中位数。时间复杂度为O(m+n) c...

weixin_30924239的博客 137

【LeetCode】修炼之路-0004-Median of Two Sorted Arrays【python】

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:Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array =

crazyjinks的博客 1125

LeetCode 4. Median of Two Sorted Arrays 题解

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

cannonjinx的博客 1009
上一篇: IIS配置httpcompression,压缩json文本提升性能
下一篇: 深入计算机系统:1.1 Information Is Bits + Context(1.1 信息就是位+的上下文)
Ken_Li_Lsq
博客等级 码龄14年 22粉丝 61原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值