Median of Two Sorted Arrays

Median of Two Sorted Arrays 題解


題目描述

Median of Two Sorted Arrays即給定兩個有序數組,尋找這個數集合的中位數。
如:[1,2] [3,4]
中位數爲2.5數組

題解

有序數組A的大小爲n,則中位數median知足
$$median = A[n / 2](n = 2k + 1)(公式1)$$
$$median = (A[(n - 1) / 2] + A[n / 2]) / 2 (n = 2k)(公式2)$$
觀察可得出一個統一分支的狀況,即將數組複製合併。A=A+A。如A=[1,2,3],那麼複製加倍後獲得A爲[1,1,2,2,3,3]。則數組A的大小永遠爲偶數,則應用(公式2)便可。spa

而在兩個數組中尋找中位數,即經過兩分猜想,驗證,捨棄便可。code

代碼

class Solution {
public:
    double findMedianSortedArrays(vector<int>& bigVec, vector<int>& smallVec) {
        int m = bigVec.size(), n = smallVec.size();
        if (m < n)
            return findMedianSortedArrays(smallVec, bigVec);
        int total = m + n;
        m <<= 1; n <<= 1;
        int left = 0, right = n;
        do {
            int midSmall = (left + right) >> 1, midBig = total - midSmall;
            int leftBig = (midBig > 0? bigVec[(midBig - 1) >> 1] : smallVec.front());
            int rightSmall = (midSmall < n? smallVec[midSmall >> 1] : bigVec.back());
            if (leftBig > rightSmall) {
                left = midSmall + 1;
                continue;
            }
            int rightBig = (midBig < m? bigVec[midBig >> 1] : smallVec.back());
            int leftSmall = (midSmall > 0? smallVec[(midSmall - 1) >> 1] : bigVec.front());
            if (leftSmall > rightBig) {
                right = midSmall - 1;
                continue;
            }
            return ((double)max(leftBig, leftSmall) + min(rightBig, rightSmall)) / 2.0;
        } while (left <= right);
        return nan(NULL);
    }
};

總結

主要應用了二分查找思想。leetcode

相關文章
相關標籤/搜索