LeetCode — Median of Two Sorted Arrays

来源:互联网 发布:人工智能 中英 百度云 编辑:程序博客网 时间:2024/06/05 08:30

Question:

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

Solution:

这里的中位数定义取决于两数组合并大小的奇偶性,如果大小为奇数,中位数为中间值;如果是偶数,有两中间值,中位数则为两中间值求均值。


方案一: 
先将两数组归并排好序,然后得出中位数,逻辑比较简单,时间复杂度为O(m+n).

方案二:
求中位数其实就是找第K小元素问题,同样用归并排序的原理,但维护一个计数,记录到找到第K个数位置停止,时间复杂度也到O(m+n).


方案三:
转化为求第K小元素问题,利用类似分治法的思想,每次剔除部分在第K小元素之前的元素,以达到优化算法的目的。此方案时间复杂度最优,为log(m+n), 实现如下:

class Solution {public:    double findMedianSortedArrays(int A[], int m, int B[], int n) {       int Num = m + n;       if (0 != Num%2)            return findKthSmallest(A, m, B, n, Num/2 + 1);       else            return (findKthSmallest(A, m, B, n, Num/2) + findKthSmallest(A, m, B, n, Num/2 + 1) )/2;    }        double findKthSmallest(int A[], int m, int B[], int n, int K)    {        if (m > n)            return findKthSmallest(B, n, A, m, K);        if (0 == m)            return B[K-1];        if (1 == K)            return A[0] > B[0] ? B[0] : A[0];        int p = min(K/2, m);        int q = K - p;        if (A[p-1] == B[q-1])            return A[p-1];        else if(A[p-1] < B[q-1])            return findKthSmallest(A + p, m - p, B, n, K - p);        else            return findKthSmallest(A, m, B + q, n -q, K - q);    }};





0 0
原创粉丝点击