LeetCode 4,LintCode 65 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)).

You may assume nums1 and nums2 cannot be both empty.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路,做到lg(m+n),一定是朝着二分去思考,每次扔掉待求位置前面的一半元素,保证二分,这里二分是对K,不同于之前数组的二分。

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int len = nums1.size() + nums2.size();
        
        if(len % 2 == 0){
            int tmp = findKth(nums1, 0, nums2, 0, len/2) 
                        + findKth(nums1, 0, nums2, 0, len/2+1);
            return tmp / 2.0;
        }
        else{
            return findKth(nums1, 0, nums2, 0, len/2+1);
        }
    }
    // 拎清楚 Kth 是从1开始,而下标是从0开始。
    // 涉及两者判断的要搞清楚边界情况
    int findKth(vector<int> &nums1, int start1, 
                vector<int> &nums2, int start2, 
                int k)
    {
        // 刚开始写的是start1 > nums1.size()-1,
        // nums1为空时通不过,因为size()返回无符号整数。
        // 菜鸡,编码不规范,AC两行泪
        if(start1 >= nums1.size()){
            return nums2[start2 + k - 1];
        }
        if(start2 >= nums2.size()){
            return nums1[start1 + k - 1];
        }
        if(k == 1){
            return min(nums1[start1], nums2[start2]);
        }

        int Start1 = nums1.size() - start1 >= k / 2 ?
                        nums1[start1 + k / 2 - 1] : INT_MAX;
        int Start2 = nums2.size() - start2 >= k / 2 ?
                        nums2[start2 + k / 2 - 1] : INT_MAX;
        if(Start1 < Start2){
            return findKth(nums1, start1 + k / 2, nums2, start2, k - k/2);
        }
        else{
            return findKth(nums1, start1, nums2, start2 + k / 2, k - k/2);
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值