1. 程式人生 > >Q4:Median of Two Sorted Arrays

Q4:Median of Two Sorted Arrays

-m nbsp ron color tar hub lan 中位數 官方

4. Median of Two Sorted Arrays

官方的鏈接:4. Median of Two Sorted Arrays

Description :

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

Example1:


nums1 = [1, 3]

nums2 = [2]

The median is 2.0


Example2:


nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5


問題描述

給定長度分別為m和n的兩個排序數組nums1和nums2,在時間復雜度O(log (m+n))內算出數組的中位數

思路

兩個有序數組的中位數和Top K問題類似。這裏從小到大直接定位第k個,簡單理解為從nums1中獲取第i個,而從nums2中獲取第j=k-i個,其中i=0~k。當定位到nums[i-1]<=nums2[j]和nums[j-1]<=nums[i]即完成,當然還有邊界問題。

把中位數也當作是top k問題,最後進行奇偶判斷。詳情可參考這裏Share my O(log(min(m,n)) solution with explanation,代碼也是借鑒的。

值得註意的是幾個邊界判斷問題,比如i為0或者m,j為0或者n。

[github-here]

 1 public class Q4_MedianOfTwoSortedArrays {
 2     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
 3 
 4         int m = nums1.length;
 5         int n = nums2.length;
 6         // make sure that m <= n
 7         if (m > n) {
 8
return findMedianSortedArrays(nums2, nums1); 9 } 10 // n>=m,i = 0 ~ m,so j = (m + n + 1) / 2 -i > 0. 11 int i = 0, j = 0, imax = m, imin = 0, halfLen = (m + n + 1) / 2; 12 int maxLeft = 0, minRight = 0; 13 while (imin <= imax) { 14 i = (imin + imax) / 2; 15 j = halfLen - i; 16 if (i < m && nums2[j - 1] > nums1[i]) { 17 imin = i + 1; 18 } else if (i > 0 && nums1[i - 1] > nums2[j]) { 19 imax = i - 1; 20 } else { 21 if (i == 0) { 22 //the target is in nums2 23 maxLeft = nums2[j - 1]; 24 } else if (j == 0) { 25 //the target is in nums1 26 maxLeft = nums1[i - 1]; 27 } else { 28 maxLeft = Math.max(nums1[i - 1], nums2[j - 1]); 29 } 30 break; 31 } 32 } 33 //odd 34 if ((m + n) % 2 == 1) { 35 return (double)maxLeft; 36 } 37 //even 38 if (i == m) { 39 //nums1 is out of index m 40 minRight = nums2[j]; 41 } else if (j == n) { 42 //nums2 is out of index n 43 minRight = nums1[i]; 44 } else { 45 //others 46 minRight = Math.min(nums1[i], nums2[j]); 47 } 48 return (double) (maxLeft + minRight) / 2; 49 } 50 51 public static void main(String[] args) { 52 new Q4_MedianOfTwoSortedArrays().findMedianSortedArrays(new int[] { 1, 3 }, new int[] { 2 }); 53 54 } 55 }

Q4:Median of Two Sorted Arrays