4. Median of Two Sorted Arrays

来源:互联网 发布:域名授权系统源码 编辑:程序博客网 时间:2024/05/22 10:44

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

第一题在leetcode的hard题目,想了很久,因为卡时间复杂度,0(log(m+n)),用什么数据结构都不行,最后想到分别从A和B中不断用2分还是啥的方法才能达到这个时间复杂度。最后也没想出来,参考了别人的思路,不断地2分k(m+n的一半),用归并的思路进行找到第k小的数(此时的k就是中位数)。

int min(int a, int b){    if(a < b)        return a;    else        return b;}double findthemink(int a[], int m, int b[], int n, int k){    if(m > n)        return findthemink(b, n, a, m, k);    if(m == 0)        return b[k - 1];    if(k == 1)        return min(a[0], b[0]);    int t1, t2;    t1 = min(m, k / 2);    t2 = k - t1;    if(a[t1 - 1] < b[t2 - 1])        return findthemink(a + t1, m - t1, b, n, k - t1);    else if(a[t1 - 1] > b[t2 - 1])        return findthemink(a, m, b + t2, n - t2, k - t2);    else        return a[t1 - 1];}double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {    int m = nums1Size, n = nums2Size;    if((m + n) % 2 == 1)        return findthemink(nums1, m, nums2, n, (m + n) / 2 + 1);    else        return (findthemink(nums1, m, nums2, n, (m + n) / 2) + findthemink(nums1, m, nums2, n, (m + n) / 2 + 1)) / 2;}
0 0
原创粉丝点击