4. Median of Two Sorted Arrays

题目链接:https://leetcode.com/problems/median-of-two-sorted-arrays/#/description

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

解题思路:其实这道题的思路倒不难,两个排好序的数组归到一个数组中,依次选取两个数组中小的一个添加到新的数组中,主要是各种细节要考虑到,比如输入的其中一个数组为空,for循环中其中一个数组遍历结束的时候……

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    double ret = 0;
    int m = nums1.size();
    int n = nums2.size();
    vector<int> ans(m+n);
    int index0 = -1, index1 = -1;
    if((m+n) % 2 == 0){
        index1 = (m+n) / 2;
        index0 = index1 - 1;
    }
    else
        index0 = (m+n-1) / 2;
    if(m==0){
        if(index1 == -1)
            return nums2[index0];
        else
            return static_cast<double>(nums2[index0]+nums2[index1])/2;
    } else if(n==0){
        if(index1 == -1)
            return nums1[index0];
        else
            return static_cast<double>(nums1[index0]+nums1[index1])/2;
    }
    else {
        int a = 0, b = 0;
        for(int i = 0; i < m+n; ++i){
            if(a < m && b < n){
                if(nums1[a] < nums2[b])
                    ans[i] = nums1[a++];
                else
                    ans[i] = nums2[b++];
            } else {
                if(a == m)
                    ans[i] = nums2[b++];
                else
                    ans[i] = nums1[a++];
            }


            if(i==index0 && index1==-1)
                return ans[i];
            else {
                if(i==index0)
                    ret = ans[i];
                else if(i==index1){
                    return static_cast<double>(ret+ans[i])/2;
                }
            }
        }
    }

    return ret;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值