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

4.Median of Two Sorted Arrays

时间:2018-11-06 01:01:10      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:code   run   mil   double   solution   复杂度   hal   基本   sans   

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

标签:code   run   mil   double   solution   复杂度   hal   基本   sans   

原文地址:https://www.cnblogs.com/Luohys/p/9912293.html

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