LeetCode Median of Two Sorted Arrays
来源:互联网 发布:最游记一键淘宝端 编辑:程序博客网 时间:2024/04/30 13:23
Median of Two Sorted Arrays
题目描述:There are two sorted arrays A and B of size mand n respectively. Find the median of the two sorted arrays. The overall runtime complexity should be O(log (m+n)).
这道题以前碰到过要求找到第K小的数。
最简单的想法就是遍历A、B两个数组,找到第K小的数。
当时做的时候也是达不到其要求的O(log(m+n))的时间复杂度。于是只能求助万能的互联网了。
这里假设A、B两个数组都是从小到大排序的,分别为{1、3、4、6、9},{2、5、7、8},要求他们第4小的数。这里先比较A的第二小的数和B的第二小的数,分别是3和5,这里就可以舍弃A的前两位数,因为他们不可能是第4大的数,于是题目就成为{4、6、9}、{2、5、7、8}找到他们第二小的数,比较A的最小和B最小的数,舍弃B最小的数,编程{4、6、9}、{5、7、8},找到他们最小的数,是4,就得到正确答案了。
public class Solution { public double findMedianSortedArrays(int A[], int B[]) { int m = A.length; int n = B.length; if(m==0&&n==0) return 0; int total = m + n; if ((total % 2)==1) return findk(A,B,total/2+1); else return (findk(A,B,total/2+1)+findk(A,B,total/2))/2.0; } double findk(int A[], int B[] ,int k){ if(A.length>B.length){//做了这个处理之后 只用考虑A数组的长度小于k/2这一种情况了。 return findk(B,A,k); } if(A.length==0){ return B[k-1]; } if(k==1){ return Math.min(A[0],B[0]); } int pa = Math.min(k/2,A.length); int pb = k-pa; if(A[pa-1]<B[pb-1]){ return findk(Arrays.copyOfRange(A,pa,A.length),B,k-pa); } else if(A[pa-1]>B[pb-1]) return findk(A,Arrays.copyOfRange(B,pb,B.length),k-pb); else return A[pa-1]; }}
0 0
- LeetCode: Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- leetcode Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [leetcode] Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- 【转载】【leetcode】Median of Two Sorted Arrays
- LeetCode - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- try---catch---finally
- 未能加载文件或程序集“Newtonsoft.Json.Net35”或它的某一个依赖项。参数错误。 (异常来自 HRESULT:0x8007
- 2014腾讯校园招聘实习笔试题
- Lua学习与交流——Lua string库经验分享
- Struts2 拦截器
- LeetCode Median of Two Sorted Arrays
- HDOJ 2243 考研路茫茫——单词情结
- 华为编程大赛-查找最大的不重复数
- 【LeetCode】Jump Game & Jump Game II
- Java中SimpleDateFormat,String.format的用法
- Server.MapPath()相关
- c2java 第6篇 图的表示,最短路,圈检测和拓扑排序
- PHP从零单排(五)PHP对数组的处理
- 杭电 1157 Who's in the Middle