博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】Median of Two Sorted Arrays(hard)★!!
阅读量:5908 次
发布时间:2019-06-19

本文共 1753 字,大约阅读时间需要 5 分钟。

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

 

思路:

难,知道用分治算法,却不知道怎么用。只好看答案。

基本的思路是如果中位数是第K个数,A[i]如果是中位数,那么A[i]已经大于了i个数,还应大于K - i - 1个数 与B[K-i-2]对比。但是如果中位数不在A中我脑子就晕晕的。下面是大神代码,我还是没有看懂。

class Solution {public:    double findMedianSortedArrays(int A[], int m, int B[], int n)    {        // the following call is to make sure len(A) <= len(B).        // yes, it calls itself, but at most once, shouldn't be        // consider a recursive solution        if (m > n)            return findMedianSortedArrays(B, n, A, m);        double ans = 0;            // now, do binary search        int k = (n + m - 1) / 2;        int l = 0, r = min(k, m); // r is n, NOT n-1, this is important!!        while (l < r) {            int midA = (l + r) / 2;            int midB = k - midA;            if (A[midA] < B[midB])                l = midA + 1;            else                r = midA;        }        // after binary search, we almost get the median because it must be between        // these 4 numbers: A[l-1], A[l], B[k-l], and B[k-l+1]         // if (n+m) is odd, the median is the larger one between A[l-1] and B[k-l].        // and there are some corner cases we need to take care of.        int a = max(l > 0 ? A[l - 1] : -(1<<30), k - l >= 0 ? B[k - l] : -(1<<30));        if (((n + m) & 1) == 1)            return (double) a;        // if (n+m) is even, the median can be calculated by         //      median = (max(A[l-1], B[k-l]) + min(A[l], B[k-l+1]) / 2.0        // also, there are some corner cases to take care of.        int b = min(l < m ? A[l] : (1<<30), k - l + 1 < n ? B[k - l + 1] : (1<<30));        return (a + b) / 2.0;    }};

 

转载地址:http://dqppx.baihongyu.com/

你可能感兴趣的文章
关于STUN和NAT
查看>>
ubuntu下添加gimp的ppa
查看>>
使用Java8实现自己的个性化搜索引擎
查看>>
龙家贰少的MarkDown学习笔记
查看>>
查看端口占用命令
查看>>
vi 常用命令
查看>>
CLRS 4.2 Exercises
查看>>
Textillate.js – 实现动感的 CSS3 文本动画的简单插件(用法详情&只支持现代浏览)...
查看>>
项目 调dubbo接口 异常总结
查看>>
通过Gearman实现MySQL到Redis的数据复制
查看>>
Peer certificate cannot be authenticated with known CA certificates
查看>>
SQLite基础
查看>>
V哥自用 测试fragment声明周期 调整懒加载
查看>>
带border的百分比布局
查看>>
SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解——跟着开涛学SpringMVC...
查看>>
html input文本只读
查看>>
Struts2访问request,session,application的四种方式
查看>>
eclipse 自动为getter和setter添加注释
查看>>
用链表实现的栈和队列
查看>>
oracle--数据库
查看>>