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

Median of Two Sorted Arrays

时间:2014-10-10 23:59:54      阅读:226      评论:0      收藏:0      [点我收藏+]

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

 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)).
1
#include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <iterator> 5 #include <unordered_map> 6 7 using namespace std; 8 9 class Solution { 10 public: 11 double findMedianSortedArrays(int A[], int m, int B[], int n) { 12 int total = m + n; 13 14 if(total & 0x01)// odd 15 return find_kth(A, m, B, n, total/2+1); 16 else// even 17 return (find_kth(A, m, B, n, total/2) + find_kth(A, m, B, n, total/2+1))/2.0; 18 } 19 private: 20 static double find_kth1(int A[], int m, int B[], int n, int k){ 21 int i = 0, j = 0, count = 0; 22 23 if(0==m) return B[k-1]; 24 if(0==n) return A[k-1]; 25 26 while(i < m && j < n){ 27 if(A[i] <= B[j]){ 28 ++count; 29 if(k==count) 30 return A[i]; 31 ++i; 32 } 33 if(A[i] >= B[j]) { 34 ++count; 35 if(k==count) 36 return B[j]; 37 ++j; 38 } 39 } 40 if(i>m-1){ 41 return B[j+k-count-1]; 42 } 43 if(j>n-1){ 44 return A[i+k-count-1]; 45 } 46 } 47 static double find_kth(int A[], int m, int B[], int n, int k){ 48 49 if(0==m) return B[k-1]; 50 if(0==n) return A[k-1]; 51 52 int alo = 0, ahi = m - 1; 53 int blo = 0, bhi = n - 1; 54 int count = 0; 55 56 while(alo <= ahi && blo <= bhi){ 57 int amid = alo + (ahi - alo) / 2; 58 int bmid = blo + (bhi - blo) / 2; 59 60 if(A[amid] <= B[bmid]){ 61 count += amid - alo + 1; 62 if(k == count) 63 return A[amid]; 64 alo = amid + 1; 65 } 66 if(A[amid] >= B[bmid]){ 67 count += bmid - blo + 1; 68 if(k == count) 69 return B[bmid]; 70 blo = bmid + 1; 71 } 72 } 73 if(alo>m-1){ 74 return B[blo+k-count-1]; 75 } 76 if(blo>n-1){ 77 return A[alo+k-count-1]; 78 } 79 } 80 }; 81 82 int main() 83 { 84 Solution s; 85 //int A[] = {1}; 86 //int B[] = {2}; 87 //int A[] = {1, 2}; 88 //int B[] = {2}; 89 int A[] = {7}; 90 int B[] = {1, 2, 3, 4, 5, 6}; 91 double res = s.findMedianSortedArrays(A, 1, B, 6); 92 //double res = s.findMedianSortedArrays(A, 1, B, 1); 93 94 cout << res; 95 96 return 0; 97 }

 

Median of Two Sorted Arrays

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

原文地址:http://www.cnblogs.com/OhFreedom/p/4017951.html

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