LeetCode Median of Two Sorted Arrays
2012-11-20 15:41
501 查看
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)).
Tips:
http://www.mitbbs.com/article/JobHunting/32203731_0.html
Solution:
class Solution {
public:
int findKth(int A[],int m,int B[],int n,int k){
if(m>n)
return findKth(B,n,A,m,k);
if(m==0)
return B[k];
if(k==0)
return min(A[0],B[0]);
int pa=min((k+1)/2,m),pb=k-pa+1;
if(A[pa-1]<B[pb-1])
return findKth(A+pa,m-pa,B,n,k-pa);
return findKth(A,m,B+pb,n-pb,k-pb);
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return (findKth(A,m,B,n,(m+n)/2)+findKth(A,m,B,n,(m+n-1)/2))*1.0/2;
}
};
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)).
Tips:
http://www.mitbbs.com/article/JobHunting/32203731_0.html
Solution:
class Solution {
public:
int findKth(int A[],int m,int B[],int n,int k){
if(m>n)
return findKth(B,n,A,m,k);
if(m==0)
return B[k];
if(k==0)
return min(A[0],B[0]);
int pa=min((k+1)/2,m),pb=k-pa+1;
if(A[pa-1]<B[pb-1])
return findKth(A+pa,m-pa,B,n,k-pa);
return findKth(A,m,B+pb,n-pb,k-pb);
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return (findKth(A,m,B,n,(m+n)/2)+findKth(A,m,B,n,(m+n-1)/2))*1.0/2;
}
};
相关文章推荐
- [Leetcode] Median of Two Sorted Arrays
- leetcode [004] : Median of Two Sorted Arrays
- [leetcode]Median of Two Sorted Arrays @ Python
- Leetcode平台上的Median of Two Sorted Arrays题目用Java堆算法实现
- [LeetCode] 4 Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- 004_LeetCode_4 Median of Two Sorted Arrays 题解
- leetcode 之Median of Two Sorted Arrays(五)
- leetcode_median of two sorted arrays
- Leetcode 4 Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- leetcode 004 Median of Two Sorted Arrays(java)
- leetcode — median-of-two-sorted-arrays
- ★leetcode04_Median of Two Sorted Arrays
- leetcode median of two sorted arrays
- LeetCode – Median of Two Sorted Arrays Java
- [leetcode] Median of Two Sorted Arrays
- LeetCode题目笔记(三) -- Median of Two Sorted Arrays
- LeetCode:Median of Two Sorted Arrays