码迷,mamicode.com
首页 > 其他好文 > 详细

Median of Two Sorted Arrays

时间:2019-09-05 00:55:11      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:turn   leetcode   size   复杂   example   ems   max   empty   res   

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.

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

题解:

  查找中位数要利用二分查找才能符合题目要求的时间复杂度

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int len1=nums1.size();
        int len2=nums2.size();
        if(len1>len2)
            return findMedianSortedArrays(nums2,nums1);
        
        int low=0,heigh=len1*2;
        int lMax1=0,rMin1=0,lMax2=0,rMin2=0;
        while(low<=heigh)
        {
            int c1=(low+heigh)>>1;
            int c2=len1+len2-c1;
            lMax1=(c1==0)?INT_MIN:nums1[(c1-1)/2];
            rMin1=(c1==2*len1)?INT_MAX:nums1[c1/2];
            lMax2=(c2==0)?INT_MIN:nums2[(c2-1)/2];
            rMin2=(c2==2*len2)?INT_MAX:nums2[c2/2];
            
            if(lMax1>rMin2)
                heigh=c1-1;
            else if(lMax2>rMin1)
                low=c1+1;
            else
                break;
        }
        return (max(lMax1,lMax2)+min(rMin1,rMin2))/2.0;
    }
};

LeetCode题解:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/4-xun-zhao-liang-ge-you-xu-shu-zu-de-zhong-wei-shu/

Median of Two Sorted Arrays

标签:turn   leetcode   size   复杂   example   ems   max   empty   res   

原文地址:https://www.cnblogs.com/tianzeng/p/11462443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!