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 = ; // now, do binary search
int k = (n + m - ) / ;
int l = , r = min(k, m); // r is n, NOT n-1, this is important!!
while (l < r) {
int midA = (l + r) / ;
int midB = k - midA;
if (A[midA] < B[midB])
l = midA + ;
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 > ? A[l - ] : -(<<), k - l >= ? B[k - l] : -(<<));
if (((n + m) & ) == )
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] : (<<), k - l + < n ? B[k - l + ] : (<<));
return (a + b) / 2.0;
}
};

最新文章

  1. 学习scala03 控制结构
  2. HTML5表单
  3. js阻止form表单重复提交
  4. Samba网络配置
  5. IMX6输出可控PWM
  6. EBS多OU和多帐套客户化总结
  7. Codeforces 519E A and B and Lecture Rooms [倍增法LCA]
  8. [xPlugins] 开发中常用富文本编辑器介绍
  9. Google实习面试归来
  10. UVALive 7352 Dance Recital
  11. AutoMapper 使用心得
  12. Tomcat异常:server Tomcat v9.09 Server at localhost failed to start
  13. PHP读取文本文件(TXT)
  14. web前端学习历程--排序
  15. JAVA002标识符的命名规则、关键字
  16. vue.js简单添加和删除
  17. linux磁盘分区详解【转】
  18. VMIC
  19. PWA(Progressive Web App)入门系列:(一)PWA简单介绍
  20. 记-cloudstack 更改二级存储

热门文章

  1. 济南学习 Day1 T3 pm
  2. linux远程客户端putty,xshell搭建注意事项——《视频》
  3. SQL 复杂查询
  4. HTML5-Geolocation&amp;地图.html
  5. C# 网卡IP(网上资料整理)
  6. PHP:strpos()-返回字符串在另一个字符串中第一次出现的位置
  7. python 数字、字符串、列表常用函数
  8. 【转】Eazfuscator.NET 3.3中混淆化需要注意的一些问题
  9. WPF 一个弧形手势提示动画
  10. 设计模式之单例模式(Singleton Pattern)