您的位置:首页 > 其它

median-of-two-sorted-arrays

2016-12-10 18:08 162 查看
排序的代价过于高,我们可以采用挪动指针的方法找到第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)).

参考了大神的代码:http://blog.csdn.net/zxzxy1988/article/details/8587244

#include <iostream>
#include <map>
#include <string>
using namespace std;

class Solution {
public:
double findMedianSortedArrays(int A[], int m,int B[], int n) {
int k = (m+n)%2;
if (k==0) return (f(A,m,B,n,(m+n)/2)+f(A,m,B,n,(m+n)/2+1))/2;
else return f(A,m,B,n,(m+n)/2+1);
}
};
double f(int a[],int m,int b[],int n,int k) {
if(m>n) return f(b,n,a,m,k);
if(m==0) return b[k-1];
if(k==1) return min(a[0],b[0]);

int pa = min(k/2,m),pb = k-pa;
if(a[pa-1]<b[pb-1]) {
return f(a+pa,m-pa,b,n,k-pa);
}
else if(b[pb-1]<a[pa-1]) {
return f(a,m,b+pb,n-pb,k-pb);
}
else return b[pb-1];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: