LeetCode : 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)).

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

代碼
分析
在這裏插入圖片描述

class Solution {
    public double findMedianSortedArrays(int[] A, int[] B) {
        int m = A.length;
        int n = B.length;
        
        // 約定A長度<=B長度,如果A長度>B長度,那麼在A取較後位置是可能會出現j小於0情況。
        if (m > n) {
            int[] temp = A; A = B; B = temp;
            int tmp = m; m = n; n = tmp;
        }
        
        //二分查找數組A
        // 數組A長度爲m,共有m+1個分割點,其中0表示都屬於右邊,m表示都屬於左邊
        int iLeft = 0, iRight = m;
        while (iLeft <= iRight) {
            //數組A的二分位置
            int i = (iLeft + iRight) / 2;
            // 根據中位值特點,數組B中j的對應位置
            int j = (m + n + 1) / 2 - i;
            
            
            // 如果i在最終結果i的的左邊,那麼對應的j就在最終結果j的右邊,
            // 此時存在A[i] < B[j-1],那麼此時應該考慮右邊區間
            if (i < iRight && B[j-1] > A[i]){
                iLeft = i + 1;
            // 如果i在最終結果i的的右邊,那麼對應的j就在最終結果j的左邊,
            // 此時存在A[i-1] > B[j],那麼此時應該考慮左邊區間
            }else if (i > iLeft && A[i-1] > B[j]) {
                iRight = i - 1;
            // 反之也就是B[j-1] <= A[i] && A[i-1] <= B[j],那麼說明找到結果了
            }else {
                int outLeft = 0;
                //如果i=0,那麼說明A中元素全屬於右邊
                if (i == 0) { outLeft = B[j-1]; }
                //如果j=0,那麼說明B中元素全屬於右邊
                else if (j == 0) { outLeft = A[i-1]; }
                // 正常情況
                else { outLeft = Math.max(A[i-1], B[j-1]); }
                // 如果是奇數,結果在左邊最大值
                if ( (m + n) % 2 == 1 ) { return outLeft; }

                
                int outRight = 0;
                // 如果i=m,那麼說明A中元素全屬於左邊
                if (i == m) { outRight = B[j]; }
                // 如果j=n,那麼說明B中元素全屬於左邊
                else if (j == n) { outRight = A[i]; }
                // 正常情況
                else { outRight = Math.min(B[j], A[i]); }

                // 如果是偶數,結果取均值
                return (outLeft + outRight) / 2.0;
            }
        }
        return 0.0;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章