Leetcode: Median of Two Sorted Arrays
来源:互联网 发布:猿粪网络语 编辑:程序博客网 时间:2024/06/08 11:16
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)).
Idea: The trivial solution is to consolidate these two sorted arrays and then find the median, then the time complexity is O(m+n) and we also need the extra space. Is there any way to utilize the properties of these two arrays: "sorted"? Tje answer is YES. A helper function will be created: findKthFromTwoSortedArrays(int A[], int starta, int enda, int B[], int startb, int endb, int k) ---- to find the k-th element from two sorted arrays.
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int mid = m+n; if( mid%2 == 0) { return (findKthFromTwoSortedArrays(A, 0, m, B, 0, n, mid/2) + findKthFromTwoSortedArrays(A, 0, m, B, 0, n, mid/2+1))/2.0; } else { return findKthFromTwoSortedArrays(A, 0, m, B, 0, n, mid/2+1); } } double findKthFromTwoSortedArrays(int A[], int starta, int enda, int B[], int startb, int endb, int k) { if(starta == enda) { return B[startb+k-1]; } if(startb == endb) { return A[starta+k-1]; } if(k == 1) return std::min(A[starta], B[startb]); int mid = k/2; int min_len = std::min(enda-starta, endb-startb); mid = std::min(mid, min_len); if(A[starta+mid-1] > B[startb+mid-1]) { return findKthFromTwoSortedArrays(A, starta, enda, B, startb+mid, endb, k-mid); } else { return findKthFromTwoSortedArrays(A, starta+mid, enda, B, startb, endb, k-mid); } }};
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
- Windows调试工具入门 — windebug
- jni中字符转换中文乱码的处理方法 Java String转换成const char*(转摘)
- 使用ZeroClipboard解决跨浏览器复制到剪贴板的问题
- 安装内核头文件
- 山东理工大学ACM平台题答案关于C语言 1194 C语言实验——余弦
- Leetcode: Median of Two Sorted Arrays
- 浅谈char *str与char str[]的区别
- centos+jdk+tomcat+jdbc
- 蜗牛—cocos2dx之HelloWorld
- Nginx部署部分https与部分http
- vs2010中的Quick Search
- Leetcode Maximum Subarray
- hud 1532 Drainage Ditches + 网络流入门题
- java虚拟机读写其它进程的数据及RandomAccessFile