两个有序数组的中位数 Median of Two Sorted Arrays
2013-10-05 23:45
453 查看
Leetcode上的一道题:
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)).
参考:
http://www.cnblogs.com/XjChenny/p/3161592.html
这道题可以扩展为两个有序数组的第K大元素
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)).
class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { // Note: The Solution object is instantiated only once and is reused by each test case. assert(m+n > 0); bool isOdd = (m+n) % 2 ; if(0==m) if(isOdd) return B[n/2]; else return (B[n/2-1]+B[n/2])/2.0; if(0==n) if(isOdd) return A[m/2]; else return (A[m/2-1]+A[m/2])/2.0; if(isOdd) { return findKthMaxNumOfArrays(A,m,B,n,(m+n+1)/2); } else { return (findKthMaxNumOfArrays(A,m,B,n,(m+n)/2)+findKthMaxNumOfArrays(A,m,B,n,(m+n)/2+1) )/2.0; } } int findKthMaxNumOfArrays(int* A,int m,int* B,int n,int k) { if(0 == m) return B[k-1]; if(0 == n) return A[k-1]; int i=m>>1, j=n>>1, *p, *q, t; if(A[i] < B[j]) p = A, q=B; else { p=B;q=A; int tmp = i; i = j; j = tmp; tmp = n; n = m; m = tmp; } t = i+j+1; if(t>=k) return findKthMaxNumOfArrays(p,m,q,j,k); else return findKthMaxNumOfArrays(p+i+1,m-i-1,q,n,k-i-1); } };
参考:
http://www.cnblogs.com/XjChenny/p/3161592.html
这道题可以扩展为两个有序数组的第K大元素
相关文章推荐
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- LeetCode OJ:Median of Two Sorted Arrays(两个有序数组的中位数)
- 两个有序数组的中位数Median of Two Sorted Arrays(很重要)
- LeetCode OJ 之 Median of Two Sorted Arrays(两个有序数组的中位数)
- [Leetcode #4]Median of Two Sorted Arrays 计算两个有序数组的中位数
- Median of Two Sorted Arrays - 寻找两个有序数组的中位数(重)
- [Leetcode #4]Median of Two Sorted Arrays 计算两个有序数组的中位数
- ~~~~(>_<)~~~~Median of Two Sorted Arrays:两个有序数组寻找中位数
- Median of Two Sorted Arrays---两个有序数组查找中位数
- Median of Two Sorted Arrays(两个有序数组的中位数)
- [LintCode] Median of Two Sorted Arrays 两个有序数组的中位数
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- Q4 Median of Two Sorted Arrays 两个有序数组的中位数
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- 《LeetBook》leetcode题解(4): Median of Two Sorted Arrays[H]——两个有序数组中值问题