# Leetcode 4 Median of Two Sorted Arrays

> 求一堆数的中位数，这一堆数分别储存在两个有序数组中。这道题要求在O(log(m + n))的时间内解决。这也是它被归为难题的原因。 那么如何在O(log(m + n))时间内求出在两个不同的有序数组中的一些数字的中位数…

- Source: https://acytoo.com/ladder/leetcode-4-median-of-two-sorted-arrays/
- Author: acytoo
- Published: 2020-06-21
- Updated: 2021-02-03
- Language: zh-CN
- Section: ladder
- Tags: leetcode, array, binary search

求一堆数的中位数，这一堆数分别储存在两个有序数组中。这道题要求在$\mathcal{O}(\log(m + n))$的时间内解决。这也是它被归为难题的原因。

那么如何在$\mathcal{O}(\log(m + n))$时间内求出在两个不同的有序数组中的一些数字的中位数呢？直接的算法，如一个个的查找，需要$\mathcal{O}(m + n)$的时间；先归并再索引中间，也是$\mathcal{O}(m + n)$时间。想达到$\mathcal{O}(\log(m + n))$的时间复杂度，可行的方法就是二分了。

这个中位数可以在任意的位置。

```cpp
static int x = [] () {ios::sync_with_stdio(false); cin.tie(0); return 0;} ();
class Solution {
 public:
  double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    const int n1 = nums1.size(), n2 = nums2.size();
    if (n2 < n1) return findMedianSortedArrays(nums2, nums1);
    const int k = (n1 + n2 + 1) >> 1;
    int l = 0, r = n1;
    while (l < r) {
      const int m1 = (l + r) >> 1, m2 = k - m1;
      if (nums1[m1] < nums2[m2 - 1])
        l = m1 + 1;
      else
        r = m1;
    }
    const int m1 = l, m2 = k - l, c1 = max(m1 == 0? INT_MIN: nums1[m1 - 1],
                                           m2 == 0? INT_MIN: nums2[m2 - 1]);
    if ((n1 + n2) & 1) return static_cast<double>(c1);
    const int c2 = min(m1 == n1? INT_MAX: nums1[m1],
                       m2 == n2? INT_MAX: nums2[m2]);
    return (c1 + c2) / 2.0;
  }
};
```

------------------
###### 直达链接

[LeetCode 4. Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)
