(算法分析Week4)Median of Two Sorted Arrays[Hard]

来源:互联网 发布:医学英文写作软件 编辑:程序博客网 时间:2024/06/01 14:40

4. Median of Two Sorted Arrays

Description

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

Solution

忽略那些直接重新排序下标的做法。
找两个有序数组的中位数,拓展到找第K大的数。上算法分析课的时候已经说过思路:
取A[k / 2] 和B[k / 2] 比较,如果 A[k / 2] > B[k / 2] 那么,所求的元素必然不在B的前k / 2个元素中
反之,不在A的前k / 2个元素中,于是我们可以将A或B数列的前k / 2元素删去,求剩下两个数列的k - k / 2小元素,于是得到了数据规模变小的同类问题,递归解决。如果 k / 2 大于某数列个数,所求元素必然不在另一数列的前k / 2个元素中。
这道题要求中位数,只需要具体化k即可,注意奇偶数。
思路虽然清晰,但是写起代码还是遇到很多问题,比如奇数偶数的处理、剩下数组不足k/2等等,需要注意。
看到有一个博客总结的很好,在这里放个网址:http://blog.csdn.net/hk2291976/article/details/51107778

Complexity analysis

O(log(m+n)),两个长度为m和n的数组。

Code

#define min(x, y) x < y?x : y#define max(x, y) x < y?y : xclass Solution {public:double findkth(vector<int>::iterator a,int m,               vector<int>::iterator 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 min(*a,*b);    int c1 = min(k/2,m),c2 = k - c1;    if(*(a + c1 - 1) < *(b + c2 -1))        return findkth(a+c1,m-c1,b,n,k-c1);    else if(*(a + c1 -1) > *(b + c2 -1))        return findkth(a,m,b+c2,n-c2,k-c2);    else        return *(a+c1-1);}double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {    auto n1 = nums1.begin();    auto n2 = nums2.begin();    int k = nums1.size() + nums2.size();    if(k % 2 == 1)        return findkth(n1,nums1.size(),n2,nums2.size(),k/2+1);    else        return (findkth(n1,nums1.size(),n2,nums2.size(),k/2) + findkth(n1,nums1.size(),n2,nums2.size(),k/2 + 1))/2;}};

Result

这里写图片描述

阅读全文
0 0
原创粉丝点击