4. 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)).

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


题目要求时间复杂度是O(log (m+n)),首先想到的就是分别从两个数组进行二分查找,但是考虑到各种边界情况,越想越复杂就放弃了。。。

这是别人的思路,时间复杂度是 O(log(min(m,n)))。

int max(int a,int b){
    if(a > b) return a;
    return b;
}
int min(int a,int b){
    if(a < b) return a;
    return b;
}
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    if(nums1Size > nums2Size){
        int* tmp = nums1;
        nums1 = nums2;
        nums2 = tmp;
        int t = nums1Size;
        nums1Size = nums2Size;
        nums2Size = t;
    }
    int mark = (nums1Size + nums2Size)%2,halfSize = (nums1Size + nums2Size + 1)/2;
    int i,j,min_of_right,max_of_left,iMin = 0,iMax = nums1Size;
    while(iMin <= iMax){
        i = (iMin + iMax)/2;
        j = halfSize - i;
        if(i < nums1Size && nums2[j-1] > nums1[i]) iMin = i + 1;
        else if(i > 0 && nums1[i-1] > nums2[j]) iMax = i - 1;
        else{
            if(i == 0) max_of_left = nums2[j-1];
            else if(j == 0) max_of_left = nums1[i-1];
            else max_of_left = max(nums1[i-1],nums2[j-1]);

            if(mark) return max_of_left/1.0;

            if(i == nums1Size) min_of_right = nums2[j];
            else if(j == nums2Size) min_of_right = nums1[i];                            
            else min_of_right = min(nums1[i],nums2[j]);

            return (max_of_left + min_of_right)/2.0;
        }
    }
    return 0.0;
}

posted @ 2018-03-24 18:13  ACLJW  阅读(89)  评论(0编辑  收藏  举报