[LeetCode] 4. Median of Two Sorted Arrays

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

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

题目:给定两个升序排列的数组nums1和nums2(长度分别为m和n),返回这两个数组的中位数,要求算法的时间复杂度是O(log(m+n))。

实现思路1(不满足时间复杂度要求):如果不考虑题目要求的时间复杂度,最直观的求解方法是将这两个有序数组合并为一个有序的大数组,然后求大数组的中位数,但数组合并过程会使时间复杂度提高至O(m+n)、空间复杂度也将提高至O(m+n)。虽然不满足题目要求,但借此机会复习一下merge sort算法。

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) throw new IllegalArgumentException("argument is null");
        int[] result = mergeSort(nums1, nums2);
        int n = result.length;
        if (n % 2 == 0)
            return (result[n / 2] + result[n / 2 - 1]) / 2.0;
        else
            return (double) result[n / 2];
        
    }
    
    private int[] mergeSort(int[] nums1, int[] nums2) {
        int n1 = nums1.length, n2 = nums2.length;
        int[] result = new int[n1 + n2];
        int i = 0, j = 0;
        for (int k = 0; k < n1 + n2; k++) {
            if (i > n1 - 1) result[k] = nums2[j++];
            else if (j > n2 - 1) result[k] = nums1[i++];
            else if (nums2[j] < nums1[i]) result[k] = nums2[j++];
            else result[k] = nums1[i++];
        }
        return result;
    }
}

实现思路2:看到时间复杂度为O(log(m+n)),自然反映是用二分查找的思想求解。具体思路主要参考LeetCode上的帖子https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2471/very-concise-ologminmn-iterative-solution-with-detailed-explanation,这个帖子讲得非常清晰,不再赘述。

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) throw new IllegalArgumentException("argument is null");
        int n1 = nums1.length;
        int n2 = nums2.length;
        if (n1 < n2) return findMedianSortedArrays(nums2, nums1);
        int lo = 0, hi = 2 * n2;
        while (lo <= hi) {
            int cut2 = lo + (hi - lo) / 2;
            int cut1 = n1 + n2 - cut2;
            double l1 = cut1 == 0 ? Integer.MIN_VALUE : nums1[(cut1 - 1) / 2];
            double r1 = cut1 == 2 * n1 ? Integer.MAX_VALUE : nums1[cut1 / 2];
            double l2 = cut2 == 0 ? Integer.MIN_VALUE : nums2[(cut2 - 1) / 2];
            double r2 = cut2 == 2 * n2 ? Integer.MAX_VALUE : nums2[cut2 / 2];
            if (l1 > r2) lo = cut2 + 1;
            else if (l2 > r1) hi = cut2 - 1;
            else return (Math.min(r1, r2) + Math.max(l1, l2)) / 2;
        }
        return -1.0;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值