2.1.5 Median of Two Sorted Arrays
来源:互联网 发布:选车软件 编辑:程序博客网 时间:2024/06/16 10:44
Link: https://oj.leetcode.com/problems/median-of-two-sorted-arrays/
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)).
Time: O(logk) = (log(m+n)/2)= O(log(m+n))
Space: O(log(m+n))//why?
这题很难。答案还没有搞懂。
public class Solution { public double findMedianSortedArrays(int A[], int B[]) { int m = A.length; int n = B.length; if((m+n)%2 == 1){ return helper(A, 0, m-1, B, 0, n-1, (m+n)/2+1); } else{ return (double)(helper(A, 0, m-1, B, 0, n-1, (m+n)/2) + helper(A, 0, m-1, B, 0, n-1, (m+n)/2+1))/2.0; } } public double helper(int[] A, int aStart, int aEnd, int[] B, int bStart, int bEnd, int k){ int aLen = aEnd - aStart + 1; int bLen = bEnd - bStart + 1; if(aLen > bLen){ return helper(B, bStart, bEnd, A, aStart, aEnd, k); } if(aLen == 0){ return B[bStart + k-1]; } if(k == 1){ return Math.min(A[aStart], B[bStart]); } int posA = Math.min(k/2, aLen); int posB = k - posA; if(A[aStart + posA - 1] < B[bStart + posB - 1]){ return helper(A, aStart+posA, aEnd, B, bStart, bEnd, k-posA); } else if(A[aStart + posA - 1] > B[bStart + posB - 1]){ return helper(A, aStart, aEnd, B, bStart+posB, bEnd, k-posB); } else{ return A[aStart + posA - 1]; } }}
0 0
- 2.1.5 Median of Two Sorted Arrays
- 2.1.5 Median of Two Sorted Arrays
- 5 leetcode - Median of Two Sorted Arrays
- 5: Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of two sorted arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- median-of-two-sorted-arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- java.lang.NoClassDefFoundError分析
- 从ffmpeg源代码分析如何解决ffmpeg编码的延迟问题
- ZOJ 3314 CAPTCHA 模拟
- 一个网站初级运营需要了解的书籍、网站、工具
- wxPython学习笔记(二)
- 2.1.5 Median of Two Sorted Arrays
- 表情配置
- 如何培养交互设计师的数据分析能力
- 最小费用最大流模板
- 科技创业公司那些上百亿美元的估值怎么算出来--夏雨青
- 如何一直保持测试工作的热情
- hdu4932 小贪心
- OHS简单安装与系统配置
- Elasticsearch索引重建(Rebuild)