前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【LeetCode题解-004】Median of Two Sorted Arrays

【LeetCode题解-004】Median of Two Sorted Arrays

作者头像
周三不加班
发布于 2019-09-04 01:59:33
发布于 2019-09-04 01:59:33
51000
代码可运行
举报
文章被收录于专栏:程序猿杂货铺程序猿杂货铺
运行总次数:0
代码可运行

1

题目

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:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
nums1 = [1, 3]
nums2 = [2]The median is 2.0

Example 2:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
nums1 = [1, 2]
nums2 = [3, 4]The median is (2 + 3)/2 = 2.5

2

词汇学习

respectively median complexity

3

惊人而又蹩脚的中文翻译

求两个有序数组的中位数,并且限制了时间复杂度为

解题思路

初看起来这就是个寻找第k小数的问题,解决方案有很多,最简单的就是采用归并排序的思想把两个数组进行合并,然后取中间的数就可以了。但问题在于,这个题目限定了时间复杂度为O(log(m+n)),而合并算法的时间复杂度为O(nlogn),显然不合题意。另外一个方法是设置一个双指针,一开始都指向两个数组的开头,不停地比较两个指针指向的元素的大小,指向小元素的指针的往前移一个元素去追指向大元素的指针,一直移动(len1+len2)/2次后就能得到中位数,但是这个算法的时间复杂度仍然不符合题意,为O(n)

但是注意到这个题目给定的数组已经是排过序的了,算法导论中对order statistic问题进行过讨论,因此,在有序又要求log级的时间复杂度,可以考虑分治策略,采用二分法。

大方向定好了,但是并不清楚具体要怎么去完成这个二分法,我们应该对什么去做二分?其实这个题目需要找的就是第k小的元素问题,假设我们的第k小的数是在第一个数组中找了p次,然后在第二个数组中找了q次,那么满足关系:p+q=k。进一步的,寻找第k小的数的过程就是寻找p和q的过程,k我们是知道的,但是p和q是不知道的,因此事实上我们的目标就是去搜索p(找到了p就等于找到了q),因此我们二分法的目标,事实上就是二分k来找p。

4

代码实现-Java

01

解法一

public static double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length, n = nums2.length, left = (m + n + 1) / 2, right = (m + n + 2) / 2; return (findKth(nums1, nums2, left) + findKth(nums1, nums2, right)) / 2.0; } public static int findKth(int[] nums1, int[] nums2, int k) { int m = nums1.length, n = nums2.length; if (m > n) { return findKth(nums2, nums1, k); } if (m == 0) { return nums2[k - 1]; } if (k == 1) { return Math.min(nums1[0], nums2[0]); } int i = Math.min(m, k / 2), j = Math.min(n, k / 2); if (nums1[i - 1] > nums2[j - 1]) { return findKth(nums1, Arrays.copyOfRange(nums2, j, n), k - j); } else { return findKth(Arrays.copyOfRange(nums1, i, m), nums2, k - i); } }

02

解法2

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public double findMedianSortedArrays_2(int[] nums1, int[] nums2) {
        int m = nums1.length, n = nums2.length;
        if (m < n) {
            return findMedianSortedArrays_2(nums2,nums1);
        }
        if (n == 0) {
            return (nums1[(m - 1) / 2] + nums1[m / 2]) / 2.0;
        }
        int left = 0, right = 2 * n;
        while (left <= right) {
            int mid2 = (left + right) / 2;
            int mid1 = m + n - mid2;
            double L1 = mid1 == 0 ? Double.MIN_VALUE : nums1[(mid1 - 1) / 2];
            double L2 = mid2 == 0 ? Double.MIN_VALUE : nums2[(mid2 - 1) / 2];
            double R1 = mid1 == m * 2 ? Double.MAX_VALUE : nums1[mid1 / 2];
            double R2 = mid2 == n * 2 ? Double.MAX_VALUE : nums2[mid2 / 2];
            if (L1 > R2) {
                left = mid2 + 1;
            } else if (L2 > R1) {
                right = mid2 - 1;
            } else {
                return (Math.max(L1, L2) + Math.min(R1, R2)) / 2;
            }
        }
        return -1;
    }
代码语言:javascript
代码运行次数:0
运行
复制

5

代码实现-Python

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

以上代码会同步更新在本人的Github和CSDN上

Github地址:https://github.com/Bylant/LeetCode

CSDN地址:https://blog.csdn.net/ZBylant

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-09-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员啊粥 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
No.004 Median of Two Sorted Arrays
4. Median of Two Sorted Arrays Total Accepted: 104147 Total Submissions: 539044 Difficulty: Hard   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
mukekeheart
2018/02/27
4660
rust leetcode median-of-two-sorted-arrays
每日小刷 median-of-two-sorted-arrays/ Runtime Memory 0ms 2.6m use std::cmp; impl Solution { // 2i + 2j = m+n // i = (m+n)/2 - j; // (m+n)/2>i // n>m 保证j > 0 pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {
用户2436820
2019/11/20
3320
leetcode 4 Median of Two Sorted Arrays
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int total = nums1.size() + nums2.size(); if (total % 2 == 1) { return findKth(nums1, 0, nums2, 0, total / 2 + 1); } els
@坤的
2018/06/04
2400
算法细节系列(8):4. Median of Two Sorted Arrays
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014688145/article/details/70159055
用户1147447
2019/05/26
4750
004. 寻找两个正序数组的中位数 | Leetcode题解
给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
苏南
2020/12/16
1.5K0
004. 寻找两个正序数组的中位数 | Leetcode题解
【每天一道编程系列-2018.2.18】(Ans)
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)). 
yesr
2019/03/14
3030
算法Code-求两个排序数组的中位数
这个思路就是对于两个有序数组进行合并,合并到一个大的有序的数组中去,然后求合并后数组的中位数。下面代码中使用的是归并排序的方式,对于两个有序数组进行归并排序的。从复杂度的角度来说可以满足题目的要求,但是还是存在一些问题,主要是怎么能够使得时间复杂度变成O{MIN(nums1.length,nums2.leng)}。
磊叔的技术博客
2025/06/07
670
算法Code-求两个排序数组的中位数
Leetcode算法系列| 4. 寻找两个正序数组的中位数
方法三中,i 和 j 每次向右移动一位时,相当于去掉了一个不可能是中位数的值,也就是一个一个的排除。由于给定的两个数组是有序的,所以我们完全可以一半一半的排除。假设我们要找第 k 小数,我们每次循环可以安全的排除掉 k/2 个数。
游戏开发小Y
2024/01/18
1500
Leetcode算法系列| 4. 寻找两个正序数组的中位数
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。   如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
xindoo
2021/01/21
2940
搞定大厂算法面试之leetcode精讲5.二分查找
搞定大厂算法面试之leetcode精讲5.二分查找 视频教程(高效学习):点击学习 目录: 1.开篇介绍 2.时间空间复杂度 3.动态规划 4.贪心 5.二分查找 6.深度优先&广度优先 7.双指针 8.滑动窗口 9.位运算 10.递归&分治 11剪枝&回溯 12.堆 13.单调栈 14.排序算法 15.链表 16.set&map 17.栈 18.队列 19.数组 20.字符串 21.树 22.字典树 23.并查集 24.其他类型题 二分搜索 时间复杂度O(logn) 步骤: 从数组中间的元素开始,如果中
全栈潇晨
2021/11/24
3390
LeetCode 004 Median of Two Sorted Arrays 详细分析
题目链接:https://leetcode.com/problems/median-of-two-sorted-arrays/
Yano_nankai
2018/12/19
1.1K0
《三战Leetcode》寻找有序数组的中位数
  大家好,又到了三分钟算法修行时间,之前挑选的算法都是中低难度的,这次找个难度较高的,看看会遇到啥问题。至于难到啥程度,来看看Leetcode下解题的网友评论。
IT学习日记
2022/09/13
3300
《三战Leetcode》寻找有序数组的中位数
LeetCode 4. 寻找两个有序数组的中位数(二分查找,难)
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Michael阿明
2020/07/13
1K0
LeetCode 4. 寻找两个有序数组的中位数(二分查找,难)
LeetCode 4 题解
请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
王小明_HIT
2020/08/18
2630
LeetCode【4】-- 寻找两个正序数组的中位数
给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
秦怀杂货店
2022/02/15
3010
LeetCode 刷题笔记——day 3
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
h-t-m
2022/11/24
2640
LeetCode 刷题笔记——day 3
LeetCode:4_Median of Two Sorted Arrays | 求两个排序数组的中位数 | Hard
题目: 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)). Subscribe to see which companies asked this question 解题思路:   我自己想的方法,先排序在查找。两个
Linux云计算网络
2018/01/11
5020
LeetCode 1-5题 详解 Java版 (三万字 图文详解 LeetCode 算法题1-5 =====>>> <建议收藏>)
给定一个数组和一个目标和,从数组中找两个数字相加等于目标和,输出这两个数字的下标。
猫头虎
2024/04/07
2430
LeetCode 1-5题 详解 Java版 (三万字 图文详解 LeetCode 算法题1-5 =====>>> <建议收藏>)
[LeetCode] 4.Median of Two Sorted Arrays
用户1148830
2018/01/03
5000
leetcode(4)寻找正序数组中位数
当然也可以创建一个大数组,然后自己实现分治算法,不过Arrays.sort底层就是分治算法(真·爆破偷懒法)。
JathonKatu
2020/10/27
2760
相关推荐
No.004 Median of Two Sorted Arrays
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档