leetcode4 O(logn)算法 the k^th smallest number in 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)).

You may assume nums1 and nums2 cannot be both empty.


解法:

假想两个数组合并成长度为m+n的nums,现在要为nums的左半部分找到int (m+n)/2个数。
假设nums1的长度比nums2小,那么操作nums1。
以二分法确定nums1的切割点。

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int m=nums1.size(), n=nums2.size();
        //保证nums1是最短的
        if(m>n) return findMedianSortedArrays(nums2, nums1);
        //操作短数组,这样长数组不会越界
        int left_num = (m + n) / 2;
        int cut1, cut2, left=0, right=m, nums1_left_max, nums1_right_min, nums2_left_max, nums2_right_min;
        while(left<=right){
            cut1 = (left + right) / 2; //左侧有cut1个数
            cut2 = left_num - cut1;
            //如何处理左右两个边界:1、哨兵(有成本)2、每次都判断
            nums1_left_max = cut1==0 ? INT_MIN : nums1[cut1-1];
            nums1_right_min = cut1==m ? INT_MAX : nums1[cut1];
            nums2_left_max = cut2==0 ? INT_MIN : nums2[cut2-1];
            nums2_right_min = cut2==n ? INT_MAX : nums2[cut2];
            //二分
            if(nums1_left_max>nums2_right_min) right = cut1 - 1; //cut1左移
            else if(nums2_left_max>nums1_right_min) left = cut1 + 1; //cut1右移
            else break; //循环条件取等号目的是永远在这里退出while
        }
        if((m+n)%2==1) return double(min(nums1_right_min, nums2_right_min));
        else return (max(nums1_left_max, nums2_left_max) + min(nums1_right_min, nums2_right_min))/2.0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值