码迷,mamicode.com
首页 > 其他好文 > 详细

Median of Two Sorted Arrays

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

标签:style   blog   color   io   ar   sp   div   on   cti   

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

标签:style   blog   color   io   ar   sp   div   on   cti   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!