Median of Two Sorted Arrays 两个数组的中位数
2014-01-18 21:48
288 查看
class Solution {
public:
double find_kth(int A[],int m,int B[],int n, int k)
{
if(m>n) return find_kth(B,n,A,m,k);
if(m==0) return B[k-1];
if(k==1) return min(A[0],B[0]);
int pa=min(m,k/2);
int pb=k-pa;
if(A[pa-1]<B[pb-1])
return find_kth(A+pa,m-pa,B,n,k-pa);
else if (A[pa-1]>B[pb-1])
return find_kth(A,m,B+pb,n-pb,k-pb);
else
return A[pa-1];
}
double findMedianSortedArrays(int A[], int m, int B[], int n)
{
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int total=m+n;
if(total%2==1)
return find_kth(A,m,B,n,total/2+1);
else
return (find_kth(A,m,B,n,total/2)+find_kth(A,m,B,n,total/2+1))/2;
}
};
public:
double find_kth(int A[],int m,int B[],int n, int k)
{
if(m>n) return find_kth(B,n,A,m,k);
if(m==0) return B[k-1];
if(k==1) return min(A[0],B[0]);
int pa=min(m,k/2);
int pb=k-pa;
if(A[pa-1]<B[pb-1])
return find_kth(A+pa,m-pa,B,n,k-pa);
else if (A[pa-1]>B[pb-1])
return find_kth(A,m,B+pb,n-pb,k-pb);
else
return A[pa-1];
}
double findMedianSortedArrays(int A[], int m, int B[], int n)
{
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int total=m+n;
if(total%2==1)
return find_kth(A,m,B,n,total/2+1);
else
return (find_kth(A,m,B,n,total/2)+find_kth(A,m,B,n,total/2+1))/2;
}
};
相关文章推荐
- 【算法导论学习-016】两个已排过序的等长数组的中位数(median of two sorted arrays)
- leetcode 4 : Median of Two Sorted Arrays 找出两个数组的中位数
- 两个有序数组的中位数Median of Two Sorted Arrays(很重要)
- Q4 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 OJ 之 Median of Two Sorted Arrays(两个有序数组的中位数)
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- Median of Two Sorted Arrays 求出两个已排序数组的中位数
- Median of Two Sorted Arrays - 寻找两个有序数组的中位数(重)
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- [LeetCode] Median of Two Sorted Arrays 两个排序数组的中位数
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- LeetCode:4_Median of Two Sorted Arrays | 求两个排序数组的中位数 | Hard
- 【LeetCode-面试算法经典-Java实现】【004-Median of Two Sorted Arrays(两个排序数组的中位数)】
- 【数组】两个排序数组的中位数Median of Two Sorted Arrays
- LeetCode | Median of Two Sorted Arrays(两个数组的中位数)
- Median of Two Sorted Arrays(求两个数组的中位数)
- Median of Two Sorted Arrays---两个有序数组查找中位数