leetcode - 4. Median of Two Sorted Arrays

Description

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

The overall run time complexity should be O(log (m+n)).

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.

Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

Constraints:

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-10^6 <= nums1[i], nums2[i] <= 10^6

Solution

Merge Sort

Calculate the final position of the median, and merge 2 sorted list to find out the median.

Time complexity: o ( n + m ) o(n+m) o(n+m)
Space complexity: o ( 1 ) o(1) o(1)

Binary Search

Refer to this video.

We have 2 lists X, Y as below:

		Px
		|
X = [x1, x2, x3, x4]
Y = [y1, y2, y3, y4, y5, y6]
					|
					Py

And we want to find a partition Px and a partition Py, where there are equal numbers at the left and right of the partition. As showed above, there are 1 element at the left of Px, and 4 elements at the left of Py, which means 5 elements at the left of partition and 5 elements at the right.

If we can find the partition, and x1 <= y5, y4 <= x2, that means all the elements at the left of the partition are smaller than the right, then we found our median.

Use binary search to find partition x, and then partition y will be: (n1 + n2 + 1)//2.

Some corner cases:

  • If the number of merged lists is odd, then we have 1 more element at the left.

  • If the number of merged lists is odd, then the median is max(x1, y4)

  • If the number of merged lists is even, the the median is avg(max(x1, y4), min(x2, y5))

  • For partition, we might have empty left or right. For example if we have the partition like this:

      	  Px
      	  |
      X = [x1, x2, x3, x4]
      Y = [y1, y2, y3, y4, y5, y6]
      						  |
      						  Py
    

    Then, we use float(-inf) to denote the number at the left of Px, similarly, float(inf) to denote the number of right half of partition.

  • The exit of binary becomes left <= right.

Code

Merge Sort

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        m, n = len(nums1), len(nums2)
        final_len = m + n
        p1, p2 = 0, 0
        p = 0
        cur_num = None
        candidates = []
        while p1 < m or p2 < n:
            if p == final_len // 2 + 1:
                candidates.append(cur_num)
            if p == final_len // 2 and final_len % 2 == 0:
                candidates.append(cur_num)
            if p1 < m and p2 < n:
                if nums1[p1] <= nums2[p2]:
                    cur_num = nums1[p1]
                    p1 += 1
                else:
                    cur_num = nums2[p2]
                    p2 += 1
            elif p1 < m:
                cur_num = nums1[p1]
                p1 += 1
            elif p2 < n:
                cur_num = nums2[p2]
                p2 += 1
            p += 1
        if p == final_len // 2 + 1:
            candidates.append(cur_num)
        if p == final_len // 2 and final_len % 2 == 0:
            candidates.append(cur_num)            
        return sum(candidates) / len(candidates)

Binary Search

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        if len(nums1) < len(nums2):
            x, y = nums1, nums2
        else:
            x, y = nums2, nums1
        n = len(nums1) + len(nums2)
        half_n = (n + 1) // 2
        left, right = 0, len(x)
        while left <= right:
            px = (left + right) >> 1
            py = half_n - px
            x_left = x[px - 1] if px > 0 else float('-inf')
            x_right = x[px] if px < len(x) else float('inf')
            y_left = y[py - 1] if py > 0 else float('-inf')
            y_right = y[py] if py < len(y) else float('inf')
            if x_left <= y_right and y_left <= x_right:
                if n & 1 == 1:
                    return float(max(x_left, y_left))
                else:
                    return (max(x_left, y_left) + min(x_right, y_right)) / 2
            elif x_left > y_right:
                right = px - 1
            elif y_left > x_right:
                left = px + 1
  • 9
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用二分查找算法来解决这个问题。 首先,我们可以将两个数组合并成一个有序数组,然后求出中位数。但是,这个方法的时间复杂度为 $O(m + n)$,不符合题目要求。因此,我们需要寻找一种更快的方法。 我们可以使用二分查找算法在两个数组中分别找到一个位置,使得这个位置将两个数组分成的左右两部分的元素个数之和相等,或者两部分的元素个数之差不超过 1。这个位置就是中位数所在的位置。 具体来说,我们分别在两个数组中二分查找,假设现在在第一个数组中找到了一个位置 $i$,那么在第二个数组中对应的位置就是 $(m + n + 1) / 2 - i$。如果 $i$ 左边的元素个数加上 $(m + n + 1) / 2 - i$ 左边的元素个数等于 $m$ 个,或者 $i$ 左边的元素个数加上 $(m + n + 1) / 2 - i$ 左边的元素个数等于 $m + 1$ 个,则这个位置就是中位数所在的位置。 具体的实现可以参考以下 Java 代码: ```java public double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length, n = nums2.length; if (m > n) { // 保证第一个数组不大于第二个数组 int[] tmp = nums1; nums1 = nums2; nums2 = tmp; int t = m; m = n; n = t; } int imin = 0, imax = m, halfLen = (m + n + 1) / 2; while (imin <= imax) { int i = (imin + imax) / 2; int j = halfLen - i; if (i < imax && nums2[j - 1] > nums1[i]) { imin = i + 1; // i 太小了,增大 i } else if (i > imin && nums1[i - 1] > nums2[j]) { imax = i - 1; // i 太大了,减小 i } else { // i 是合适的位置 int maxLeft = 0; if (i == 0) { // nums1 的左边没有元素 maxLeft = nums2[j - 1]; } else if (j == 0) { // nums2 的左边没有元素 maxLeft = nums1[i - 1]; } else { maxLeft = Math.max(nums1[i - 1], nums2[j - 1]); } if ((m + n) % 2 == 1) { // 总元素个数是奇数 return maxLeft; } int minRight = 0; if (i == m) { // nums1 的右边没有元素 minRight = nums2[j]; } else if (j == n) { // nums2 的右边没有元素 minRight = nums1[i]; } else { minRight = Math.min(nums1[i], nums2[j]); } return (maxLeft + minRight) / 2.0; } } return 0.0; } ``` 时间复杂度为 $O(\log\min(m, n))$。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值