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

Median of Two Sorted Arrays

时间:2014-07-31 12:14:56      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   cti   ar   div   size   

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 public class Solution {
 2     public double findMedianSortedArrays(int A[], int B[]) {
 3         int alen = A.length;
 4         int blen = B.length;
 5         if((alen + blen) % 2 == 1) return findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen + 1) / 2);
 6         else return (double) (findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen) / 2) + findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen + 2) / 2)) / 2.0;
 7     }
 8     private int findKthElement(int arra[], int arrb[], int ast, int and, int bst, int bnd, int num){
 9         if(ast > and) return arrb[bst + num - 1];
10         if(bst > bnd) return arra[ast + num - 1];
11         int amid = (ast + and) / 2;
12         int bmid = (bst + bnd) / 2;
13         int len = amid - ast + 1 + bmid - bst + 1;
14         if(arra[amid] < arrb[bmid]){
15             if(len <= num) return findKthElement(arra, arrb, amid + 1, and, bst, bnd, num - amid + ast - 1);
16             else return findKthElement(arra, arrb, ast, and, bst, bmid - 1, num);
17         }else{
18             if(len <= num) return findKthElement(arra, arrb, ast, and, bmid + 1, bnd, num - bmid + bst - 1);
19             else return findKthElement(arra, arrb, ast, amid - 1, bst, bnd, num);
20         }
21     }
22 }

 

Median of Two Sorted Arrays,布布扣,bubuko.com

Median of Two Sorted Arrays

标签:style   blog   color   io   cti   ar   div   size   

原文地址:http://www.cnblogs.com/reynold-lei/p/3880003.html

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