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

4.Median of Two Sorted Arrays

查找 解法 find san spec code sof else complex

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

You may assume nums1 and nums2 cannot be both empty.

Example 1:

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

The median is 2.0

Example 2:

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

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

求兩個排序數組的中位數。題目關鍵是時間復雜度要求O(log (m+n))。
想了好久好像有點思路但是又不明確,看了下官方解答,解法確實比較巧。

二分查找

規定了復雜度,基本就是二分查找了。

這道題的思路就是:兩個數組A,B的中位數,左邊和右邊的數的個數肯定是相等的,如果左邊的數有i個來自數組A,那麽就有(len(A) + len(B))/2-i個來自數組B。

只要確定來自數組A的最大值小於等於數組B中余下的最小值就可以了。

可以配合代碼理解:

 1 public class Solution {
 2     public double FindMedianSortedArrays(int
[] nums1, int[] nums2) { 3 int m = nums1.Length; 4 int n = nums2.Length; 5 if (m > n) 6 { 7 return FindMedianSortedArrays(nums2, nums1); 8 } 9 int min = 0; 10 int max = m; 11 int half = (m + n + 1) / 2; 12 while
(min <= max) 13 { 14 int i = (min + max) / 2; 15 int j = half - i; 16 if (i < max && nums1[i] < nums2[j - 1]) 17 { 18 min = i + 1; 19 } 20 else if (i > min && nums1[i - 1] > nums2[j]) 21 { 22 max = i - 1; 23 } 24 else 25 { 26 int maxLeft = 0; 27 if (i == 0) 28 { 29 maxLeft = nums2[j - 1]; 30 } 31 else if (j == 0) 32 { 33 maxLeft = nums1[i - 1]; 34 } 35 else 36 { 37 maxLeft = Math.Max(nums1[i - 1], nums2[j - 1]); 38 } 39 if (((m + n) & 1) == 1) 40 { 41 return maxLeft; 42 } 43 44 int minRight = 0; 45 if (i == m) 46 { 47 minRight = nums2[j]; 48 } 49 else if (j == n) 50 { 51 minRight = nums1[i]; 52 } 53 else 54 { 55 minRight = Math.Min(nums1[i], nums2[j]); 56 } 57 return (maxLeft + minRight) / 2d; 58 } 59 } 60 return 0d; 61 } 62 }

也可以通過直接比較兩個數組的中位數來進行二分查找,時間復雜度都是O(log (min(m+n))),就不再贅述了。(主要是語言描述太麻煩=_=)

4.Median of Two Sorted Arrays