【Leetcode】4. Median of Two Sorted Arrays

Problem

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

Understanding

Median, 在統(tǒng)計(jì)學(xué)中叫做中位數(shù),能夠?qū)⒁粋€(gè)數(shù)列分成不包含其自身的兩個(gè)部分,兩個(gè)部分長(zhǎng)度相等。如果是處理一個(gè)有序數(shù)組,則如果數(shù)組長(zhǎng)度為奇數(shù),則取中間位,如果為偶數(shù)則取中間兩數(shù)的均值。

測(cè)試用例

[1,3]
[2,3]
2.5

[1,10]
[2,3]
2.5

解法

歸并排序通過(guò)合并兩個(gè)有序的數(shù)列得到一個(gè)新有序數(shù)列,這就是解法的思想。然后取中間的一位或者兩位的均值。
不過(guò),與歸并排序的不同的是,并不需要實(shí)際的合并,只需要找到最后數(shù)組的中間一位或者兩位數(shù)即可。使用兩個(gè)變量last,cur來(lái)記錄即可。
空間復(fù)雜度O(1), 時(shí)間復(fù)雜度O(m+n)

代碼(C++)

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        const int length=nums1.size()+nums2.size();
        
        const int indexEnd=(length%2==0)?(length+1)/2:length/2;
        int i1=0,i2=0;
        int index=0;
        int cur,last;
        while(i1 < nums1.size() && i2<nums2.size() && index <=indexEnd )
        {
            index++;
            last=cur;
            if(nums1[i1]>nums2[i2])
                cur=nums2[i2++];
            else
                cur=nums1[i1++];
        }
        while(i1 < nums1.size() && index <=indexEnd)
        {
            last=cur;
            cur=nums1[i1++];
            index++;
        }
        while(i2 < nums2.size() && index <= indexEnd)
        {
            last=cur;
            cur=nums2[i2++];
            index++;
        }
        return length%2==0?(last+cur)/2.0:cur;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容