问题描述:

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

解题思路:

看到时间复杂度的时候就知道这种应该使用二分查找法了,否则如果实现log的时间复杂度?

思路已经有大神提供了,说的非常清楚,附上链接地址:http://my.oschina.net/jdflyfly/blog/283267

代码如下:

public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int total = nums1.length + nums2.length;
if (total % 2 == 0)
return (findKth(nums1, 0, nums1.length - 1, nums2, 0,
nums2.length - 1, total / 2) + findKth(nums1, 0,
nums1.length - 1, nums2, 0, nums2.length - 1, total / 2 + 1)) / 2;
else
return findKth(nums1, 0, nums1.length - 1, nums2, 0,
nums2.length - 1, total / 2 + 1); } public double findKth(int[] a, int astart, int aend, int[] b,
int bstart, int bend, int k) {
if (aend - astart > bend - bstart)
return findKth(b, bstart, bend, a, astart, aend, k);
if (astart > aend)
return b[k - 1];
if (k == 1)
return a[astart] > b[bstart] ? b[bstart] : a[astart];
else {
int la = Math.min(k / 2, aend - astart + 1);
int lb = k - la;
if (a[astart + la - 1] == b[bstart + lb - 1])
return a[astart + la - 1];
else if (a[astart + la - 1] < b[bstart + lb - 1])
return findKth(a, astart + la, aend, b, bstart, bend, k - la);
else
return findKth(a, astart, aend, b, bstart + lb, bend, k - lb);
} }
}

最新文章

  1. 读取properties文件以及properties的用法
  2. BOM,文档宽高及窗口事件小析
  3. 水溶彩铅的特点&amp;技法运用
  4. ajax轮询session阻塞问题
  5. [转]Java并发的四种风味:Thread、Executor、ForkJoin和Actor
  6. Android Audio Play Out Channel
  7. hdu 2818 Building Block(加权并查集)2009 Multi-University Training Contest 1
  8. .Net平台-MVP模式初探(一)
  9. P2P结构与Quorum机制------《Designing Data-Intensive Applications》读书笔记8
  10. 纯代码实现WordPress评论回复自动添加@评论者的功能
  11. 【安卓开发】Android为什么选择binder
  12. PageHelper分页插件及通用分页js
  13. [20190329]探究sql语句相关mutexes补充2.txt
  14. Django restframework之Token验证的缺陷及jwt的简单使用
  15. js运用5
  16. 并发之lock的condition接口
  17. 携程Apollo配置中心架构深度剖析
  18. hybrid浅记
  19. Eclipse中java文件和jsp字体大小设置
  20. HDFS上传数据的流程

热门文章

  1. 如何通过热修复,搞定开发中的那些 Bug?
  2. 【面试题003】c数组做为参数退化的问题,二维数组中的查找
  3. Const和ReadOnly区别及其用途--转载
  4. SPOJ LCS2 后缀自动机
  5. Project Euler 95:Amicable chains 亲和数链
  6. HDU5093——Battle ships(最大二分匹配)(2014上海邀请赛重现)
  7. redhat 安装telnet服务
  8. LA 6042 Bee Tower 记忆化搜索
  9. hibernate--lazy(懒加载)属性
  10. C#实现GDI+基本图的缩放、拖拽、移动