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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容

  • 青春年少,难免会有叛逆萌发的冲动,细数过往便以长大,时光数栽,我们临近而立之年,不曾想过还有多少青春值得留念,...
    踏过青春那条河阅读 148评论 0 0
  • 夜近了,天暗了。 我翻了翻书桌上崭新的书本,拿起了又放下。电脑屏幕打开的光把我的脸打的彤红,手机不停地闪过扣扣信息...
    朝夕骏阅读 101评论 0 0
  • 前几天,语文节到了,我们进行了一次语文节的考试,里面考的题目五花八门,有看图猜成语,有看拼音写词语,还有古诗词...
    黎天曜阅读 203评论 2 2
  • Singleton pattern 限定类对象只有一个实例核心原理是将构造函数私有化,并且通过静态方法获取一个唯一...
    wangdy12阅读 174评论 0 0