每天一道leetcode-求兩個已經(jīng)排列好的數(shù)組的中值

問題描述

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個最小數(shù)
這里提供另外一種想法

想法

把數(shù)組a b 都分為兩個數(shù)組 ,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]
    滿足這兩個條件之后,很容易得到兩個數(shù)組得中值 ,也就是如果數(shù)組是奇數(shù)的話,就是a[i-1],b[j-1]較大的那個,如果是偶數(shù),就是兩者相加除以2.

問題就轉(zhuǎn)換到了如何分成滿足這兩個條件的數(shù)組,也就是找到合適的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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容