LeetCode:Median of Two Sorted Arrays
来源:互联网 发布:windows允许ruby 编辑:程序博客网 时间:2024/05/22 05:33
题目描述:
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)).
思路:写一个找两个数组中第k大数的函数,每次至少可以在数组A或数组B中排除min(m,n,k/2)个元素。递归调用该函数,直到k=1或者A、B中一个元素为空。
代码:
double Solution::findMedianSortedArrays(int A[], int m, int B[], int n){ return (find_Kth(A,m,B,n,(m+n+1)/2) + find_Kth(A,m,B,n,(m+n+2)/2)) / 2.0;}int Solution::find_Kth(int A[],int m,int B[],int n,int k){ if(m == 0) return B[k-1]; if(n == 0) return A[k-1]; if(k == 1) return min(A[0],B[0]); int i = min(m,k/2); int j = min(n,k/2); if(A[i-1] > B[j-1]) return find_Kth(A,m,B+j,n-j,k-j); else return find_Kth(A+i,m-i,B,n,k-i);}
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
- 高效的jQuery代码编写技巧总结
- Java的23种设计模式
- C++ 智能指针详解
- [C++对象模型][3]指针与数组
- 浅析Log Buffer
- LeetCode:Median of Two Sorted Arrays
- 编写单向链表
- Thrift 文件的格式及可用的数据类型
- java 解析xml字符串(dom4j)
- c语言起泡排序
- [C++对象模型][4]指针与字符串
- linux shell基本文件处理
- Hadoop最大值的算法中出现的错误(strToDouble)
- linux的进程散列表