4. Median of Two Sorted Arrays

来源:互联网 发布:如果世上不再有猫 知乎 编辑:程序博客网 时间:2024/06/07 01:11

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
如果没有时间复杂度的要求,完全可以用merge的思想,把两个数组合并成一个,再进行遍历。但是这道题的时间复杂度要求是O(log (m+n)),得用binary search的思想。怎么找是关键。首先,假设数组A和B的元素个数都大于k/2,我们比较A[k/2-1]和B[k/2-1]两个元素,这两个元素分别表示A的第k/2小的元素和B的第k/2小的元素。这两个元素比较共有三种情况:>、<和=。如果A[k/2-1]<B[k/2-1],这表示A[0]到A[k/2-1]的元素都在A和B合并之后的前k小的元素中。换句话说,A[k/2-1]不可能大于两数组合并之后的第k小值,所以我们可以将其抛弃。

进一步来想,先看下图,两个中位数 A[m/2] 和 B[n/2], 可以将数组划分为四个部分。而丢弃哪一个部分取决于两个条件:1, (m/2 + n/2)?k;2,A[m/2] ? B[n/2];:


如果 (m/2 + n/2) > k,那么意味着,当前中位数取高了,正确的中位数要么在 Section 1或者Section3中。如果A[m/2] > B[n/2], 意味着中位数肯定不可能在Section 2里面,那么新的搜索可以丢弃这个区间段了。同理可以推断出余下三种情况,如下所示:

If (m/2+n/2+1) > k && am/2 > bn/2 , drop Section 2
If (m/2+n/2+1) > k && am/2 < bn/2 , drop Section 4
If (m/2+n/2+1) < k && am/2 > bn/2 , drop Section 3
If (m/2+n/2+1) < k && am/2 < bn/2 , drop Section 1

懂了这个道理,就可以看懂下面这段代码:

public class Solution {    public double findMedianSortedArrays(int[] nums1, int[] nums2) {        int m = nums1.length, n = nums2.length;        if ((m + n) % 2 == 1) {            return findNth(nums1, 0, nums2, 0, (m + n) / 2 + 1);        } else {            return (findNth(nums1, 0, nums2, 0, (m + n) / 2) + findNth(nums1, 0, nums2, 0, (m + n) / 2 + 1)) / 2;        }    }    public double findNth(int[] a, int astart, int[] b, int bstart, int k) {        if (a.length - astart > b.length - bstart) {            return findNth(b, bstart, a, astart, k);        }        if (a.length - astart == 0) {            return b[k - 1];        }        if (k == 1) {            return Math.min(a[astart], b[bstart]);        }        int pa = Math.min(k / 2, a.length - astart), pb = k - pa;        if (a[astart + pa - 1] < b [bstart + pb - 1]) {            return findNth(a, astart + pa, b, bstart, k - pa);        } else if (a[astart + pa - 1] > b [bstart + pb - 1]) {            return findNth(a, astart, b, bstart + pb, k - pb);        } else {            return a[pa - 1];        }    }}
引:http://blog.csdn.net/yutianzuijin/article/details/11499917

http://fisherlei.blogspot.com/2012/12/leetcode-median-of-two-sorted-arrays.html

0 0
原创粉丝点击