Median of Two Sorted Arrays

Posted tianzeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

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的主要内容,如果未能解决你的问题,请参考以下文章

leedcode Median of Two Sorted Arrays

#Leetcode# 4. Median of Two Sorted Arrays

LeetCode: Median of Two Sorted Arrays

** Median of Two Sorted Arrays

Leetcode 4. Median of Two Sorted Arrays(二分)

4. Median of Two Sorted Arrays