美文网首页
每天一道leetcode-求两个已经排列好的数组的中值

每天一道leetcode-求两个已经排列好的数组的中值

作者: autisticBoy | 来源:发表于2019-01-24 20:10 被阅读0次

问题描述

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

在我的一篇博客中提供了类似的方法找到第K个最小数
这里提供另外一种想法

想法

把数组a b 都分为两个数组 ,a分为a[0] - a[i-1] , a[i] - a[m-1];b分为b[0] - b[j-1],b[j] - b[n-1];
满足下列两个条件

  • i + j = m - i + n - j 也就是 j = (m+n) / 2 - j;
  • 左边的小于右边的 也就是a[i-1] < b[j]; b[j-1] < a[i]
    满足这两个条件之后,很容易得到两个数组得中值 ,也就是如果数组是奇数的话,就是a[i-1],b[j-1]较大的那个,如果是偶数,就是两者相加除以2.

问题就转换到了如何分成满足这两个条件的数组,也就是找到合适的i,也就是找到满足第二个条件的i

找i方法

找[imin,imax]

  • 如果a[i-1] > b[j],就要减少也就是imax = i - 1; 找[imin, i-1];
  • 如果a[i] < b[j-1] i要增大 就是找[i+1,imax],也就是imin = i + 1;

代码

class Solution {
    public double findMedianSortedArrays(int[] A, int[] B) {
        int m = A.length;
        int n = B.length;
        if (m > n) { // to ensure m<=n
            int[] temp = A; A = B; B = temp;
            int tmp = m; m = n; n = tmp;
        }
        int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2;
        while (iMin <= iMax) {
            int i = (iMin + iMax) / 2;
            int j = halfLen - i;
            if (i < iMax && B[j-1] > A[i]){
                iMin = i + 1; // i is too small
            }
            else if (i > iMin && A[i-1] > B[j]) {
                iMax = i - 1; // i is too big
            }
            else { // i is perfect
                int maxLeft = 0;
                if (i == 0) { maxLeft = B[j-1]; }
                else if (j == 0) { maxLeft = A[i-1]; }
                else { maxLeft = Math.max(A[i-1], B[j-1]); }
                if ( (m + n) % 2 == 1 ) { return maxLeft; }

                int minRight = 0;
                if (i == m) { minRight = B[j]; }
                else if (j == n) { minRight = A[i]; }
                else { minRight = Math.min(B[j], A[i]); }

                return (maxLeft + minRight) / 2.0;
            }
        }
        return 0.0;
    }
}

相关文章

网友评论

      本文标题:每天一道leetcode-求两个已经排列好的数组的中值

      本文链接:https://www.haomeiwen.com/subject/yamujqtx.html