004 Median of Two Sorted Arrays [Leetcode]

来源:互联网 发布:营销软件广告 编辑:程序博客网 时间:2024/05/30 05:28

题目内容:

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

解题思路:
复杂度要求为O(log (m+n)),很容易让人想到二分查找。如果是一个长度为(m+n)的排序数组,那么直接使用二分查找就可以。但本题是在两个数组上进行的,那么在两个数组上进行二分查找会如何呢?
找中位数,若为奇数个,就是找第(m+n)/2个数;若为偶数个,就是找第(m+n)/2和第(m+n)/2+1个数的平均值。设我们要找的数是第k个。
1. 如果第一个数组的中间值与第二个数组的中间值相同,那么说明我们找到了中间值,即中间的这个数。
2. 如果第一个数组的中间值小于第二个数组的中间值,说明第一个数组中间值以前都不可能是前k个数,因此在剩余的数组中继续找前k-m/2个数
3. 如果第一个数组的中间值大于第二个数组的中间值,说明第二个数组中间值以前都不可能是前k个数,因此在剩余的数组中继续找前k-n/2个数
4. 注意处理数组变为空的情况

代码如下:

class Solution {public:    double findMedianSortedArrays(int A[], int m, int B[], int n) {        int length(m+n);        if(length%2)            return findKth(A, m, B, n, length/2+1);        else            return (findKth(A, m, B, n, length/2)+findKth(A, m, B, n, length/2+1))/2.0;    }    int findKth(int A[], int m, int B[], int n, int K) {        if(m>n)            return findKth(B, n, A, m, K);        if(m==0)            return B[K-1];        if(K==1)            return A[0]<B[0]?A[0]:B[0];        int pa(K/2<m?K/2:m);        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(A, m, B+pb, n-pb, K-pb);        else            return findKth(A+pa, m-pa, B, pb, K-pa);    }};
0 0
原创粉丝点击