LeetCode_4_findMedianSortedArrays

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。

请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1 和 nums2 不会同时为空。

示例 1:

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

则中位数是 2.0
示例 2:

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

则中位数是 (2 + 3)/2 = 2.5

  • 解题思路

1.如果不考虑时间复杂度,直接对两个数组进行排序,然后返回中位数

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] nums = new int[nums1.length + nums2.length];
        int index = 0, index1 = 0, index2 = 0;
        while(index1 < nums1.length && index2 < nums2.length){
            if(nums1[index1] < nums2[index2]){
                nums[index++] = nums1[index1++];
            }else{
                nums[index++] = nums2[index2++];
            }
        }
        while(index1 < nums1.length){
            nums[index++] = nums1[index1++];
        }
        while(index2 < nums2.length){
            nums[index++] = nums2[index2++];
        }
        double res = 0;
        if(index % 2 == 0){
            res = (nums[nums.length / 2] + nums[nums.length / 2 - 1]) / 2.0;
        }else{
            res = nums[nums.length / 2];
        }
        return res;
    }
}

2.考虑时间复杂度,要求为O(log(m+n))。看到logm,首先想到折半查找。

给定两个已经排好序的数组nums1、nums2,要找到这两个数组的中位数。

把nums1分成两部分,左边的元素L1<右边的元素R1

把nums2分成两部分,左边的元素L2<右边的元素R2

只要保证L1和L2中最大的元素<R1和R2中最小的元素,那么中位数就可以找到了(L1和L2中元素个数=两个数组元素总个数的一半)

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if(nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1);
        int len = nums1.length + nums2.length;
        int cut1 = 0, cut2 = 0;         //cut1,cut2分别表示nums1,nums2划分处左侧的元素个数
        int cutL = 0, cutR = nums1.length;          //cutL,cutR表示nums1二分的左右范围
        while(cut1 <= nums1.length){
            cut1 = (cutR - cutL) / 2 + cutL;
            cut2 = len / 2 - cut1;
            double l1 = (cut1 == 0) ? Integer.MIN_VALUE : nums1[cut1 - 1];
            double l2 = (cut2 == 0) ? Integer.MIN_VALUE : nums2[cut2 - 1];
            double r1 = (cut1 == nums1.length) ? Integer.MAX_VALUE : nums1[cut1];
            double r2 = (cut2 == nums2.length) ? Integer.MAX_VALUE : nums2[cut2];
            if(l1 > r2){
                cutR = cut1 - 1;
            }else if(l2 > r1){
             }else{
                if(len % 2 == 0){
                    l1 = l1 > l2 ? l1 : l2;
                    r1 = r1 < r2 ? r1 : r2;
                    return (l1 + r1) / 2.0;
                }else{
                    r1 = r1 < r2 ? r1 : r2;
                    return r1;
                }
            }
        }
        return 0;
    }
}          cutL = cut1 + 1;
     

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值