首页 > 其他 > 详细

Median of Two Sorted Arrays

时间:2014-10-19 18:17:38      阅读:227      评论:0      收藏:0      [点我收藏+]

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)).

code:

 1 class Solution {
 2 public:
 3     double findMedianSortedArrays(int A[], int m, int B[], int n) {
 4         int total = m + n;
 5         if(total & 1)
 6             return find_kth(A, m, B, n, total/2 + 1);
 7         else return (find_kth(A, m, B, n, total/2) + find_kth(A, m, B, n, total/2 + 1))/2.0;
 8     }
 9     int find_kth(int A[], int m, int B[], int n, int k){
10         if(m > n) return find_kth(B, n, A, m, k);
11         if(m == 0) return B[k-1];
12         if(k == 1) return min(A[0], B[0]);
13         
14         int ia = min(k/2, m);
15         int ib = k - ia;
16         
17         if(A[ia-1] < B[ib-1])
18             return find_kth(A+ia, m-ia, B, n, k - ia);
19         else if(A[ia-1] > B[ib-1])
20                 return find_kth(A, m, B+ib, n-ib, k - ib);
21         else return A[ia-1];
22     }
23 };

 

Median of Two Sorted Arrays

原文:http://www.cnblogs.com/Kai-Xing/p/4035101.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!