LeetCode 4. Median of Two Sorted Arrays

来源:互联网 发布:2k16樱木花道捏脸数据 编辑:程序博客网 时间:2024/06/06 01:52

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

题目要求时间复杂度为O(log(m+n)),应该是二分查找来做的。除了比较Low的方法外,还没想到比较好的方法。
在这一题的Discuss里面看到一种二分查找的方法,时间复杂度是O(log(m+n)),传送门。下面附上代码。

在Discuss中还看到一种方法,先取中间数,而后找中位数的方法,解释得比较详细,我一开始也是这样想的,觉得太烦了,但是这个方法处理得很好,不过它的时间复杂度应该是O(min(m,n)) 的,跟题目要求不符,传送门

Mark一下,我要多多学习。

class Solution {public:    int getkth(int s[], int m, int l[], int n, int k){        if (m > n)            return getkth(l, n, s, m, k);        if (m == 0)            return l[k-1];        if (k == 1)            return min(s[0], l[0]);        int i = min(m, k/2), j = min(n, k/2);        if (s[i-1] > l[j-1])            return getkth(s, m, l + j, n-j, k-j);        else            return getkth(s+i, m-i, l, n, k-i);        return 0;    }    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2){        int m = nums1.size();        int n = nums2.size();        vector<int>::iterator iter;        int A[m+1],B[n+1],i;        memset(A,0,sizeof(A));        memset(B,0,sizeof(B));        for(i=0,iter=nums1.begin();iter!=nums1.end();i++,iter++){            A[i]=*iter;        }        for(i=0,iter=nums2.begin();iter!=nums2.end();i++,iter++){            B[i]=*iter;        }        int l = (m+n+1) >> 1;        int r = (m+n+2) >> 1;        return (getkth(A, m ,B, n, l) + getkth(A, m, B, n, r)) / 2.0;    }};
原创粉丝点击