median

median

排序的代价过于高,我们可以采用挪动指针的方法找到第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)).
参考了大神的代码:

#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];
}

发布者:admin,转转请注明出处:http://www.yc00.com/news/1705479544a1411401.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信