Median of Two Sorted Arrays

Median of Two Sorted Arrays

问题:

There are two sorted arrays A and B 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)).

思路:

  二分查找变形

我的代码:

public class Solution {
    public double findMedianSortedArrays(int A[], int B[]) {
        int lenA = A.length;
        int lenB = B.length;
        if((lenA+lenB)%2 == 1) return (double)findKth(A,B,(lenA+lenB)/2+1);
        else return (findKth(A,B,(lenA+lenB)/2+1) + findKth(A,B,(lenA+lenB)/2))/(double)2;
    }
    public int findKth(int[] a, int[] b, int k)
    {
        int lenA = a.length;
        int lenB = b.length;
        if(lenA > lenB) return findKth(b, a, k);
        if(lenA == 0) return b[k-1];
        if(k == 1) return Math.min(a[0],b[0]);
        int pa = Math.min(k/2,lenA);
        int pb = k - pa;
        if(a[pa-1] == b[pb-1]) return a[pa-1];
        else if(a[pa-1] < b[pb-1]) return findKth(Arrays.copyOfRange(a, pa, lenA), b, k - pa);
        else return findKth(a, Arrays.copyOfRange(b, pb, lenB), k - pb);
    }
}
View Code

 学习之处:

  • 今天下午状态不好,想了一会没有思路,就直接看答案了,之前肯定是用二分查找的问题,没想到二分查找也等价于二分排除嘛!这一点没有意识到。
  • 原题被转换成经典的找两个sorted的数组中 K大的数,不断的去排除掉不符合的部分
  • 首先假设数组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[k/2-1]>B[k/2-1]。当A[k/2-1]=B[k/2-1]的时候,A[k/2 - 1]即为第K个大的数
原文地址:https://www.cnblogs.com/sunshisonghit/p/4390321.html