[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)容合作請聯(lián)系作者
  • 序言:七十年代末躬贡,一起剝皮案震驚了整個濱河市刽肠,隨后出現(xiàn)的幾起案子丈屹,更是在濱河造成了極大的恐慌,老刑警劉巖肌厨,帶你破解...
    沈念sama閱讀 211,743評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異兆解,居然都是意外死亡帅韧,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,296評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來煌茴,“玉大人随闺,你說我怎么就攤上這事÷” “怎么了矩乐?”我有些...
    開封第一講書人閱讀 157,285評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長回论。 經(jīng)常有香客問我散罕,道長,這世上最難降的妖魔是什么傀蓉? 我笑而不...
    開封第一講書人閱讀 56,485評論 1 283
  • 正文 為了忘掉前任欧漱,我火速辦了婚禮,結(jié)果婚禮上僚害,老公的妹妹穿的比我還像新娘硫椰。我一直安慰自己繁调,他們只是感情好萨蚕,可當我...
    茶點故事閱讀 65,581評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蹄胰,像睡著了一般岳遥。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上裕寨,一...
    開封第一講書人閱讀 49,821評論 1 290
  • 那天浩蓉,我揣著相機與錄音,去河邊找鬼宾袜。 笑死捻艳,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的庆猫。 我是一名探鬼主播认轨,決...
    沈念sama閱讀 38,960評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼月培!你這毒婦竟也來了嘁字?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,719評論 0 266
  • 序言:老撾萬榮一對情侶失蹤杉畜,失蹤者是張志新(化名)和其女友劉穎纪蜒,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體此叠,經(jīng)...
    沈念sama閱讀 44,186評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡纯续,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,516評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片猬错。...
    茶點故事閱讀 38,650評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡牙丽,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出兔魂,到底是詐尸還是另有隱情烤芦,我是刑警寧澤,帶...
    沈念sama閱讀 34,329評論 4 330
  • 正文 年R本政府宣布析校,位于F島的核電站构罗,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏智玻。R本人自食惡果不足惜遂唧,卻給世界環(huán)境...
    茶點故事閱讀 39,936評論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望吊奢。 院中可真熱鬧盖彭,春花似錦、人聲如沸页滚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,757評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽裹驰。三九已至隧熙,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間幻林,已是汗流浹背贞盯。 一陣腳步聲響...
    開封第一講書人閱讀 31,991評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留沪饺,地道東北人躏敢。 一個月前我還...
    沈念sama閱讀 46,370評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像整葡,于是被迫代替她去往敵國和親件余。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,527評論 2 349

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

  • 青春年少掘宪,難免會有叛逆萌發(fā)的沖動蛾扇,細數(shù)過往便以長大,時光數(shù)栽魏滚,我們臨近而立之年镀首,不曾想過還有多少青春值得留念,...
    踏過青春那條河閱讀 149評論 0 0
  • 夜近了鼠次,天暗了更哄。 我翻了翻書桌上嶄新的書本芋齿,拿起了又放下。電腦屏幕打開的光把我的臉打的彤紅成翩,手機不停地閃過扣扣信息...
    朝夕駿閱讀 101評論 0 0
  • 前幾天觅捆,語文節(jié)到了,我們進行了一次語文節(jié)的考試麻敌,里面考的題目五花八門栅炒,有看圖猜成語,有看拼音寫詞語术羔,還有古詩詞...
    黎天曜閱讀 211評論 2 2
  • Singleton pattern 限定類對象只有一個實例核心原理是將構(gòu)造函數(shù)私有化赢赊,并且通過靜態(tài)方法獲取一個唯一...
    wangdy12閱讀 175評論 0 0