Java [leetcode 4] Median of Two Sorted Arrays
2024-10-16 02:07:53
问题描述:
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);
} }
}
最新文章
- 读取properties文件以及properties的用法
- BOM,文档宽高及窗口事件小析
- 水溶彩铅的特点&;技法运用
- ajax轮询session阻塞问题
- [转]Java并发的四种风味:Thread、Executor、ForkJoin和Actor
- Android Audio Play Out Channel
- hdu 2818 Building Block(加权并查集)2009 Multi-University Training Contest 1
- .Net平台-MVP模式初探(一)
- P2P结构与Quorum机制------《Designing Data-Intensive Applications》读书笔记8
- 纯代码实现WordPress评论回复自动添加@评论者的功能
- 【安卓开发】Android为什么选择binder
- PageHelper分页插件及通用分页js
- [20190329]探究sql语句相关mutexes补充2.txt
- Django restframework之Token验证的缺陷及jwt的简单使用
- js运用5
- 并发之lock的condition接口
- 携程Apollo配置中心架构深度剖析
- hybrid浅记
- Eclipse中java文件和jsp字体大小设置
- HDFS上传数据的流程
热门文章
- 如何通过热修复,搞定开发中的那些 Bug?
- 【面试题003】c数组做为参数退化的问题,二维数组中的查找
- Const和ReadOnly区别及其用途--转载
- SPOJ LCS2 后缀自动机
- Project Euler 95:Amicable chains 亲和数链
- HDU5093——Battle ships(最大二分匹配)(2014上海邀请赛重现)
- redhat 安装telnet服务
- LA 6042 Bee Tower 记忆化搜索
- hibernate--lazy(懒加载)属性
- C#实现GDI+基本图的缩放、拖拽、移动