[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)).

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

</br>

Solution

The objective of the problem is to find the median of the combination of two sorted arrays, therefore the most obvious way to solve this problem is to first combine these two sorted arrays and then decide which is the median of the new array.

However, this method may lack in efficiency for we will waste time on re-sorting the array. We need something better than this. The goal is to find median under O(log (m+n)) time so we cannot simply insert the element from array B into array A; instead, we should try to achieve this in one pass.

Hence, the solution can be established.

Firstly, consider how to determine a median of an array: median is the number at the middle position of a sorted array. Hence, we only have to find the middle element of the combination of two array. Instead of re-sorting two arrays, we can divide both sorted arrays into two parts, as nums1[0,i],nums1[i,m],nums2[0,j]and nums2[j,n] and then put nums1[0,i] and nums2[0,j] in one set, nums1[i,m] and nums2[j,n] into another.

        Left_set         |          Right_set
A[0], A[1], ..., A[i-1]  |  A[i], A[i+1], ..., A[m-1]
B[0], B[1], ..., B[j-1]  |  B[j], B[j+1], ..., B[n-1]

As two arrays are sorted, we only have to achieve requirements below in order to find the right median.
[a]. The maximum of the left_set is smaller than the minimum of the right_set;
[b]. The size of the left_size and right_set should be the same.

If the above the requirements is achieved, then we simply have to compute the median by median = (max(left_part) + min(right_part))/2.

Then, the next issue we have to deal with is how to make sure the requirement is met. Then, to ensure these two conditions, we just need to ensure:

(1)   i + j == m - i + n - j  (or: m - i + n - j + 1)
(2)   B[j-1] <= A[i] && A[i-1] <= B[j]

Therefore, we can have following steps.

[1] Set min = 0, max = m; then the search range is [min, max].

[2] Set i = (min + max)/2, j = (m + n + 1)/2 - i. 
     //By setting the value of i and j in this way, 
     //we can make sure the length of both set is equal.

[3] There are only 3 situations to deal with:
    <a> B[j-1] <= A[i] and A[i-1] <= B[j]
        Indicates the right `i`, return median;

    <b> B[j-1] > A[i]
        Indicates A[i] is too small. 
        We must adjust i to get B[j-1] <= A[i], hence we must increase i.
        By adjusting the search range to [i+1, max], B[j-1] is decreased and A[i] is increased, and B[j-1] <= A[i] may be satisfied.
        So, set min = i+1, and goto <2>.

    <c> A[i-1] > B[j]
        Indicates A[i-1] is too big. And we must decrease i to achieve A[i-1]<=B[j].
        So we must adjust the search range to [min, i-1].
        Set max = i-1, and goto <2>.

By adjusting the value of i and j, we can find where is the right place to divide two arrays.

When the right i is found, the median should be:

(when m + n is odd)
      max(A[i-1], B[j-1]) ;
(when m + n is even)
      (max(A[i-1], B[j-1]) + min(A[i], B[j]))/2 ;

The code is shown as below:
Java

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        
        int m = nums1.length, n = nums2.length;
        int max_of_left = 0, min_of_right = 0;
        
        if (m > n){
            int[] temp = nums1;
            nums1 = nums2;
            nums2 = temp;
            int temp_num = m;
            m = n;
            n = temp_num;
        }
    
        int min = 0, max = m, mid = (m + n + 1) / 2;
        
        while (min <= max){
            int i = (min + max) / 2;
            int j = mid - i;
            
            if (i < m && nums2[j-1] > nums1[i])
                // i is too small
                min = i + 1;
            else if (i > 0 && nums1[i-1] > nums2[j])
                // i is too big
                max = i - 1;
            else{
                // i is perfect
                if (i == 0) 
                    max_of_left = nums2[j-1];
                else if (j == 0)
                    max_of_left = nums1[i-1];
                else
                    max_of_left = Math.max(nums1[i-1], nums2[j-1]);
    
                if ((m + n) % 2 == 1)
                    return max_of_left;
    
                if (i == m) 
                    min_of_right = nums2[j];
                else if (j == n)
                    min_of_right = nums1[i];
                else 
                    min_of_right = Math.min(nums1[i], nums2[j]);
    
                return (max_of_left + min_of_right) / 2.0;
            }
        }    
        return 0;
    }
}

</br>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,619評(píng)論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,155評(píng)論 3 425
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 177,635評(píng)論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 63,539評(píng)論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,255評(píng)論 6 410
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 55,646評(píng)論 1 326
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,655評(píng)論 3 444
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 42,838評(píng)論 0 289
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,399評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,146評(píng)論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,338評(píng)論 1 372
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,893評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,565評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 34,983評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 36,257評(píng)論 1 292
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,059評(píng)論 3 397
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,296評(píng)論 2 376

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

  • 青春年少,難免會(huì)有叛逆萌發(fā)的沖動(dòng),細(xì)數(shù)過(guò)往便以長(zhǎng)大,時(shí)光數(shù)栽,我們臨近而立之年,不曾想過(guò)還有多少青春值得留念,...
    踏過(guò)青春那條河閱讀 155評(píng)論 0 0
  • 夜近了,天暗了。 我翻了翻書(shū)桌上嶄新的書(shū)本,拿起了又放下。電腦屏幕打開(kāi)的光把我的臉打的彤紅,手機(jī)不停地閃過(guò)扣扣信息...
    朝夕駿閱讀 102評(píng)論 0 0
  • 前幾天,語(yǔ)文節(jié)到了,我們進(jìn)行了一次語(yǔ)文節(jié)的考試,里面考的題目五花八門,有看圖猜成語(yǔ),有看拼音寫(xiě)詞語(yǔ),還有古詩(shī)詞...
    黎天曜閱讀 229評(píng)論 2 2
  • Singleton pattern 限定類對(duì)象只有一個(gè)實(shí)例核心原理是將構(gòu)造函數(shù)私有化,并且通過(guò)靜態(tài)方法獲取一個(gè)唯一...
    wangdy12閱讀 181評(píng)論 0 0