LeetCode 算法第四题

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

Code

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    int n = (nums1Size >= nums2Size) ? nums1Size : nums2Size;
    int m = nums1Size + nums2Size - n;
    int *sn = (nums1Size >= nums2Size) ? nums1 : nums2;
    int *sm = (nums1Size < nums2Size) ? nums1 : nums2;
    int imin, imax, i, j, ihalf, max_left, min_right;
    imin = 0; imax = m; ihalf = (m + n + 1)/2;
    while(imin <= imax){
        i=(imin + imax)/2;
        j=ihalf-i;
        if(i<m && sn[j-1]>sm[i])
            imin = i+1;
        else if(i > 0 && sm[i-1]>sn[j])
            imax = i-1;
        else{
            if(i == 0)
                max_left = sn[j-1];
            else if(j == 0)
                max_left = sm[i-1];
            else
                max_left = (sn[j-1] > sm[i-1]) ? sn[j-1] : sm[i-1];

            if((m+n)%2 == 1)
                return max_left;

            if(i == m)
                min_right = sn[j];
            else if(j == n)
                min_right = sm[i];
            else
                min_right = (sn[j] < sm[i]) ? sn[j] : sm[i];

            return (min_right + max_left)/2.0;
        }
    }
    return 0;
}

Reference

@MISSMARY的分析

Discussion

  1. Understand the definition and find out the essential need of the problem.
  2. pseudo-code
  3. special cases analysis
  4. coding

猜你喜欢

转载自blog.csdn.net/gaussrieman123/article/details/78527942
今日推荐