首页 > 其他 > 详细

Median of Two Sorted Arrays

时间:2015-08-15 21:17:47      阅读:174      评论: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)).

思路:将原问题转变成找两个升序数组第k小数的问题。

 1 public class Solution {
 2         public double findMedianSortedArrays(int[] nums1, int[] nums2) {
 3             int len = nums1.length + nums2.length;
 4             if((len&1) == 1) {
 5                 return findKth(nums1, 0, nums1.length-1, nums2, 0, nums2.length-1, len / 2 + 1);
 6             } else {
 7                 return findKth(nums1, 0, nums1.length-1, nums2, 0, nums2.length-1, len / 2) / 2 + 
 8                 findKth(nums1, 0, nums1.length-1, nums2, 0, nums2.length-1, len / 2 + 1) / 2;
 9             }
10         }
11         
12         public double findKth(int[] nums1, int left1, int right1, int[] nums2, int left2, int right2, int k) {
13             int len1 = right1 - left1 + 1;
14             int len2 = right2 - left2 + 1;
15             //always assume that m is equal or smaller than n
16             if(len1 > len2) return findKth(nums2, left2, right2, nums1, left1, right1, k);
17             if(len1 == 0) return nums2[left2 + k -1];
18             if(k == 1) return Math.min(nums1[left1], nums2[left2]);
19             //divide k into two parts 
20             int part1 = Math.min(k/2, len1);
21             int part2 = k - part1;
22             int index1 = left1 + part1 - 1;
23             int index2 = left2 + part2 - 1;
24             if(nums1[index1] < nums2[index2]) return findKth(nums1, index1+1, right1, nums2, left2, right2, k-part1);
25             else if(nums1[index1] > nums2[index2]) return findKth(nums1, left1, right1, nums2, index2+1, right2, k-part2);
26             else return nums1[index1];
27         }
28     }

 在最好情况下,每次都有k一半的元素被删除,所以算法复杂度为logk,由于求中位数时k为(m+n)/2,所以算法复杂度为log(m+n)。

Median of Two Sorted Arrays

原文:http://www.cnblogs.com/ivanyangzhi/p/4733028.html

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