Leetcode:Median of Two Sorted Arrays

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
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5

問題解析及算法描述

本題爲兩個有序數組合並後的中位數,若先不考慮時間複雜度的話,只需要從小到大依次數(m+n)/2個元素,從而轉化成經典的找第k小的數的問題。
算法如下:同時遍歷兩個有序數組,比較數組的兩個數的大小,若其中一個數組的數比較小則記錄該數同時該數組的下標加一(即往後遍歷新的數),否則記錄另一數同時往後遍歷另一個數組,直至遍歷總數爲(m+n)/2時;接下來,只需判斷總數爲奇數還是偶數,從而求得結果。

代碼及其他算法實現

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int size1 = nums1.size(), size2 = nums2.size();
        int n = size1+ size2;
        int m = n/2;
        int v1 =0,v2 = 0;
        vector<int>::iterator it1 = nums1.begin(), it2 = nums2.begin();
        for (int i = 0; i  <= m; i++) {
            v1 = v2;
            if(it1 < nums1.end() && it2 < nums2.end()) {
                if (*it1 > *it2) {
                    v2 = *it2;
                    it2++;
                } else {
                    v2 = *it1;
                    it1++;
                }
            } else if (it1 < nums1.end()) {
                v2 = *it1;
                it1++;
            } else if (it2 < nums2.end()) {
                v2 = *it2;
                it2++;
            }
        }

        double median;
        if (n%2 == 0) median = (v1+v2)/2.0f;
        else median = v2;
        return median;
    }
};

注意:該代碼應用了歸併計數算法複雜度爲O((m+n)/2),並不符合題目要求的O(log(m+n))
因此,可採用分治算法解決兩個有序數組中的中位數和Top K問題(該鏈接博主的思路比較清晰易懂)實現O(log(m+n))的複雜度,代碼如下:

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int n = nums1.size();
        int m = nums2.size();
        if(n > m)   //保證數組1一定最短
            return findMedianSortedArrays(nums2,nums1);
        int L1,L2,R1,R2,c1,c2,lo = 0, hi = 2*n;  //我們目前是虛擬加了'#'所以數組1是2*n長度
        while(lo <= hi)   //二分
        {
            c1 = (lo+hi)/2;  //c1是二分的結果
            c2 = m+n- c1;
            L1 = (c1 == 0)?INT_MIN:nums1[(c1-1)/2];   //map to original element
            R1 = (c1 == 2*n)?INT_MAX:nums1[c1/2];
            L2 = (c2 == 0)?INT_MIN:nums2[(c2-1)/2];
            R2 = (c2 == 2*m)?INT_MAX:nums2[c2/2];

            if(L1 > R2)
                hi = c1-1;
            else if(L2 > R1)
                lo = c1+1;
            else
                break;
        }
        return (max(L1,L2)+ min(R1,R2))/2.0;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章