首页 > 编程语言 > 详细

Java [leetcode 4] Median of Two Sorted Arrays

时间:2015-04-25 15:01:44      阅读:242      评论:0      收藏:0      [点我收藏+]

问题描述:

There are two sorted arrays nums1 and nums2 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)).

解题思路:

看到时间复杂度的时候就知道这种应该使用二分查找法了,否则如果实现log的时间复杂度?

思路已经有大神提供了,说的非常清楚,附上链接地址:http://my.oschina.net/jdflyfly/blog/283267

代码如下:

 1 public class Solution {
 2     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
 3         int total = nums1.length + nums2.length;
 4         if (total % 2 == 0)
 5             return (findKth(nums1, 0, nums1.length - 1, nums2, 0,
 6                     nums2.length - 1, total / 2) + findKth(nums1, 0,
 7                     nums1.length - 1, nums2, 0, nums2.length - 1, total / 2 + 1)) / 2;
 8         else
 9             return findKth(nums1, 0, nums1.length - 1, nums2, 0,
10                     nums2.length - 1, total / 2 + 1);
11 
12     }
13 
14     public double findKth(int[] a, int astart, int aend, int[] b,
15             int bstart, int bend, int k) {
16         if (aend - astart > bend - bstart)
17             return findKth(b, bstart, bend, a, astart, aend, k);
18         if (astart > aend)
19             return b[k - 1];
20         if (k == 1)
21             return a[astart] > b[bstart] ? b[bstart] : a[astart];
22         else {
23             int la = Math.min(k / 2, aend - astart + 1);
24             int lb = k - la;
25             if (a[astart + la - 1] == b[bstart + lb - 1])
26                 return a[astart + la - 1];
27             else if (a[astart + la - 1] < b[bstart + lb - 1])
28                 return findKth(a, astart + la, aend, b, bstart, bend, k - la);
29             else
30                 return findKth(a, astart, aend, b, bstart + lb, bend, k - lb);
31         }
32 
33     }
34 }

 

Java [leetcode 4] Median of Two Sorted Arrays

原文:http://www.cnblogs.com/zihaowang/p/4455798.html

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