leetcode 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

题意:给定两个已排序数组,找出中间的数(即可以将两个有序数组分成左右数目相同的两部分的数)
思路:使用二分搜索从较短的数组中找出合适的划分,时间复杂度为O(min(len1, len2))。

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int len1 = nums1.size(), len2 = nums2.size();
        if (len1 < len2) return findMedianSortedArrays(nums2, nums1);

        int low = 0, high = len2 * 2;//从较短数组的最大元素开始
        while (low <= high) {
            int mid2 = (low + high) / 2;
            int mid1 = len1 + len2 - mid2;//确保划分后左侧元素个数等于右侧元素个数
            //第一次划分,分别取较长数组和较短数组的中间数
            double l1 = (mid1 == 0) ? INT_MIN : nums1[(mid1-1)/2];
            double l2 = (mid2 == 0) ? INT_MIN : nums2[(mid2-1)/2];
            double r1 = (mid1 == len1 * 2) ? INT_MAX : nums1[mid1/2];
            double r2 = (mid2 == len2 * 2) ? INT_MAX : nums2[mid2/2];

            if (l1 > r2) low = mid2 + 1;//若较长数组的左侧最大值大于较短数组的右侧最小值,说明较短数组划分位置应右移,即low=mid2+1;
            else if (l2 > r1) high = mid2 - 1;//若较短数组的左侧最大值大于较长数组的右侧最小值,说明较短数组的划分位置应左移,即high=mid2-1;
            else return (max(l1,l2) + min(r1, r2)) / 2;
        }
        return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值