LeetCode—寻找两个有序数组中值
2014-08-21 20:29
363 查看
Median of Two Sorted Arrays
There are
two sorted arrays A and B 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)).
题目很简单,重点是是时间的控制上,首先是想到了比较简单的方法class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int * a = new int[m+n];
memcpy(a,A,m*sizeof(int));
memcpy(a+m,B,n*sizeof(int));
sort(a,a+m+n);
double returnValue =(double) ((n+m)%2? a[(n+m)>>1]:(a[(n+m-1)>>1]+a[(n+m)>>1])/2.0);
delete a;
return returnValue;
}
};
这个方法,将两个数组进行重新排列,因为是用到的sort函数,但是事实上不好的情况下是十分耗时的,最坏情况为O(nlogn)
之后想到了一些经典的算法,比如归并算法,这里感觉还是比较有用
采用递归的方式进行计算,比较两个数组的中值,如果median[A]<median[B],那么可以说明A数组的前半截数据不可能是中值,因此可以舍弃,利用递归函数进行实现
下面是考虑到一些特殊的情况:
如果A或者B为空,则直接返回B[k-1]或者A[k-1];
如果k为1,我们只需要返回A[0]和B[0]中的较小值;
如果A[k/2-1]=B[k/2-1],返回其中一个;
同时在代码中我们保持长度较小的数组在前面
double findKth(int a[], int m, int b[], int n, int k)
{
//always assume that m is equal or smaller than n
if (m > n)
return findKth(b, n, a, m, k);
if (m == 0)
return b[k - 1];
if (k == 1)
return min(a[0], b[0]);
//divide k into two parts
int pa = min(k / 2, m), pb = k - pa;
if (a[pa - 1] < b[pb - 1])
return findKth(a + pa, m - pa, b, n, k - pa);
else if (a[pa - 1] > b[pb - 1])
return findKth(a, m, b + pb, n - pb, k - pb);
else
return a[pa - 1];
}
class Solution
{
public:
double findMedianSortedArrays(int A[], int m, int B[], int n)
{
int total = m + n;
if (total & 0x1)
return findKth(A, m, B, n, total / 2 + 1);
else
return (findKth(A, m, B, n, total / 2)
+ findKth(A, m, B, n, total / 2 + 1)) / 2;
}
};
在最好情况下,每次都有k一半的元素被删除,所以算法复杂度为logk,由于求中位数时k为(m+n)/2,所以算法复杂度为log(m+n)。
相关文章推荐
- 【leetcode】——从两个有序数组中寻找他们并集的第k小元素
- [LeetCode题解]从两个有序数组的并集中寻找第k小元素
- leetcode—从两个有序数组中寻找他们并集的第k小元素(思路)
- leetcode之数组类之数组的旋转与分治类-----OJ 189/33/81/153/154 数组旋转 旋转数组搜索 88 有序数组合并 4 两个有序数组寻找第K个元素/中位数 35 寻找插入位置
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- 【leetcode】Merge Sorted Array(合并两个有序数组到其中一个数组中)
- 数据结构与算法[LeetCode]—两个有序数组合并及找中点问题
- [LeetCode]4 两个有序数组的中位数
- [转载]寻找两个有序数组中的第K个数或者中位数
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- leetcode | Median of Two Sorted Arrays 寻找2个有序数组中第k大的值
- [leetcode]Merge Sorted Array (两个有序数组的合并 C语言实现)
- 两个有序数组寻找合并之后第k大的数
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- 寻找两个有序数组中的第K个数或者中位数
- 在两个有序数组中寻找第k个元素
- 算法——寻找两个有序数组的中值
- Median of Two Sorted Arrays - 寻找两个有序数组的中位数(重)
- [LeetCode-34] Search for a Range (寻找有序数组中关键值的索引范围)
- leetcode 两个有序数组合成