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

Median of Two Sorted Arrays

时间:2014-09-10 17:36:20      阅读:172      评论:0      收藏:0      [点我收藏+]

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

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

思路:转化为两个有序列第K大的值。

 1 class Solution {
 2 public:
 3     double findMedianSortedArrays( int A[], int m, int B[], int n ) {
 4         int a1 = FindKthNum( (m+n-1)/2, A, m, B, n );
 5         int a2 = FindKthNum( (m+n)/2, A, m, B, n );
 6         return ( a1 + a2 ) / 2.0;
 7     }
 8 private:
 9     int FindKthNum( int k, const int* A, int m, const int* B, int n ) {
10         if( m == 0 ) { return B[k]; }
11         if( n == 0 ) { return A[k]; }
12         if( k == 0 ) { return A[0] < B[0] ? A[0] : B[0]; }
13         int k1 = -1, k2 = -1;
14         if( m < n ) {
15             k1 = min( k/2, m-1 ), k2 = k - k1 - 1;
16         } else {
17             k2 = min( k/2, n-1 ), k1 = k - k2 - 1;
18         }
19         if( A[k1] < B[k2] ) {
20             return FindKthNum( k2, &A[k1+1], m-k1-1, &B[0], k2+1 );
21         } else if( A[k1] > B[k2] ) {
22             return FindKthNum( k1, &A[0], k1+1, &B[k2+1], n-k2-1 );
23         }
24         return B[k2];
25     }
26 };

 

Median of Two Sorted Arrays

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

原文地址:http://www.cnblogs.com/moderate-fish/p/3960852.html

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