您的位置:首页 > 其它

leetcode [004] : Median of Two Sorted Arrays

2015-09-13 09:36 281 查看
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)).

时间复杂度不为log(m+n)也能够通过leetcode的测试,也就是使用简单的合并排序,然后取中位数

不过本题,如果要log(m+n)的时间复杂度的话,需要使用第k小算法

思路:

1、假设第一个数组的数据个数总是小于第二个数组

2、当第一个数组的数字个数为0时,返回nums2[k - 1];

3、当k为1时候,返回min(nums1[0], nums2[0]);

4、如果不是以上三种情况,则每次去掉k/2个数字(每次去掉一半,时间复杂度变为log级)

注:证明可以去掉那k / 2个数字可以具体参见http://blog.csdn.net/yutianzuijin/article/details/11499917/ 总之网上很多

源代码如下:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Solution {
public:

double findKth(vector<int>& nums1, int start1, vector<int>& nums2, int start2, int k)
{
int iLen1 = nums1.size() - start1;
int iLen2 = nums2.size() - start2;
if (iLen2 < iLen1)
{
return findKth(nums2, start2, nums1, start1, k);
}
if (iLen1 == 0)
{
return nums2[k - 1];
}
if (k == 1)
{
return min(nums1[start1], nums2[start2]);
}

int pa = min(k / 2, iLen1);
int pb = k - pa;
if (nums1[start1 + pa - 1] == nums2[start2 + pb -1])
{
return nums1[start1 + pa - 1];
}
else if (nums1[start1 + pa - 1] < nums2[start2 + pb -1])
{
return findKth(nums1, start1 + pa, nums2, start2, k - pa);
}
else
{
return findKth(nums1, start1, nums2, start2 + pb, k - pb);
}
}

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int iLen1 = nums1.size();
int iLen2 = nums2.size();
int iMidNum = (iLen1 + iLen2) / 2;
if ((iLen1 + iLen2) & 0x01)
{
return findKth(nums1, 0, nums2, 0, iMidNum + 1);
}
else
{
return (findKth(nums1, 0, nums2, 0, iMidNum) + findKth(nums1, 0, nums2, 0, iMidNum + 1)) / 2;
}
}
};

int main()
{
vector<int> vec1;
vector<int> vec2;
vec1.push_back(1);
vec1.push_back(7);
vec1.push_back(9);
vec2.push_back(1);
vec2.push_back(3);
vec2.push_back(5);

Solution a;
double lfMedian = a.findMedianSortedArrays(vec1, vec2);
printf("%f\n", lfMedian);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: