LeetCode_4_Median of Two Sorted Arrays

(This question difficult)
Title Description: There are two rows of sequences have been sorted and nums1 nums2, sizes are m, n, to find the median of the two sequences has been sorted, the time complexity is required O (log (m + n) ). You can assume nums1 and nums2 two sequences can not be empty.

输入样例1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
输入样例2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

Prior to solve the problem, we need to understand what role the median?
The median is used to distinguish one set into two subsets of the same length, and the two subsets of elements of a subset of less than all of the elements to a further subset; i.e., length (subSet1) == length (subSet2 ) and max (subSet1) <= min ( subSet2)

Implementation code

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int m=nums1.size();
        int n=nums2.size();
        if(m>n){
            vector<int> temp=nums1;
            nums1=nums2;
            nums2=temp;
            int tem=m;
            m=n;
            n=tem;
        }
        int iMin=0,iMax=m,half=(m+n+1)/2;
        while(iMin<=iMax){
            int i=(iMin+iMax)/2;
            int j=half-i;
            if(i<iMax&&nums2[j-1]>nums1[i]){
                iMin=i+1;
            }
            else if(i>iMin&&nums1[i-1]>nums2[j]){
                iMax=i-1;
            }
            else{
                int maxLeft=0;
                if(i==0){maxLeft=nums2[j-1];}
                else if(j==0){maxLeft=nums1[i-1];}
                else{maxLeft=max(nums1[i-1],nums2[j-1]);}
                if((m+n)%2==1){return maxLeft;}
                int minRight=0;
                if(i==m){minRight=nums2[j];}
                else if(j==n){minRight=nums1[i];}
                else{minRight=min(nums2[j],nums1[i]);}
                return (maxLeft+minRight)/2.0;
            }
        }
        return 0.0;
    }
};

Runtime Chart

Guess you like

Origin blog.csdn.net/all_about_WZY/article/details/88326575