Leetcode: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

问题解析及算法描述

本题为两个有序数组合并后的中位数,若先不考虑时间复杂度的话,只需要从小到大依次数(m+n)/2个元素,从而转化成经典的找第k小的数的问题。
算法如下:同时遍历两个有序数组,比较数组的两个数的大小,若其中一个数组的数比较小则记录该数同时该数组的下标加一(即往后遍历新的数),否则记录另一数同时往后遍历另一个数组,直至遍历总数为(m+n)/2时;接下来,只需判断总数为奇数还是偶数,从而求得结果。

代码及其他算法实现

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int size1 = nums1.size(), size2 = nums2.size();
        int n = size1+ size2;
        int m = n/2;
        int v1 =0,v2 = 0;
        vector<int>::iterator it1 = nums1.begin(), it2 = nums2.begin();
        for (int i = 0; i  <= m; i++) {
            v1 = v2;
            if(it1 < nums1.end() && it2 < nums2.end()) {
                if (*it1 > *it2) {
                    v2 = *it2;
                    it2++;
                } else {
                    v2 = *it1;
                    it1++;
                }
            } else if (it1 < nums1.end()) {
                v2 = *it1;
                it1++;
            } else if (it2 < nums2.end()) {
                v2 = *it2;
                it2++;
            }
        }

        double median;
        if (n%2 == 0) median = (v1+v2)/2.0f;
        else median = v2;
        return median;
    }
};

注意:该代码应用了归并计数算法复杂度为O((m+n)/2),并不符合题目要求的O(log(m+n))
因此,可采用分治算法解决两个有序数组中的中位数和Top K问题(该链接博主的思路比较清晰易懂)实现O(log(m+n))的复杂度,代码如下:

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int n = nums1.size();
        int m = nums2.size();
        if(n > m)   //保证数组1一定最短
            return findMedianSortedArrays(nums2,nums1);
        int L1,L2,R1,R2,c1,c2,lo = 0, hi = 2*n;  //我们目前是虚拟加了'#'所以数组1是2*n长度
        while(lo <= hi)   //二分
        {
            c1 = (lo+hi)/2;  //c1是二分的结果
            c2 = m+n- c1;
            L1 = (c1 == 0)?INT_MIN:nums1[(c1-1)/2];   //map to original element
            R1 = (c1 == 2*n)?INT_MAX:nums1[c1/2];
            L2 = (c2 == 0)?INT_MIN:nums2[(c2-1)/2];
            R2 = (c2 == 2*m)?INT_MAX:nums2[c2/2];

            if(L1 > R2)
                hi = c1-1;
            else if(L2 > R1)
                lo = c1+1;
            else
                break;
        }
        return (max(L1,L2)+ min(R1,R2))/2.0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值