您的位置:首页 > 其它

Leetcode-4 Median of Two Sorted Arrays

2016-12-21 21:54 337 查看

Leetcode-4 Median of Two Sorted Arrays

Problem:

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
2.nums1 = [1, 2],nums2 = [3, 4],The median is (2 + 3)/2 = 2.5


时间复杂度需要O(log(m+n)), 应该想到二分的时间复杂度。

查找中位数,即将两个数组中的所有数的第(n+m)/ 2小的数,转换成求第k个数问题。

对于排好序的两个数组a, b来说,查找第k小的数

1.如果a[k/2] < b[k/2], 则b[k/2]可能为第k小数,而a[k /2]则不可能,应该继续在a[k/2 , N]和b[0, M]范围查找第K-K/2小数, 否则在a[0, N]和b[k/2, M]范围查找

2.如果a, b剩余范围长度有小于k/2的,假设是b, 则比较b[M] 和 a[k-M]的大小;若b[M] < a[k-M],在a[0, N]里面查找第k-M小数,否则在b[0, M]和a[k-M, N]范围查找

class Solution {
public:
int find_kth(vector<int> &a, int beg1, vector<int> &b, int beg2, int k) {
//cout << beg1 << " " << beg2 << " " << k << endl;
if(b.size() - beg2 > a.size() - beg1)
return find_kth(b, beg2, a, beg1, k);
if(beg2 == b.size())
return a[beg1+k-1];
if(k == 1)
return min(a[beg1], b[beg2]);

int i = min(k/2, (int)b.size() - beg2);
int j = k - i;
if(a[beg1+j-1] < b[beg2+i-1])
return find_kth(a, beg1+j, b, beg2, k-j);
return find_kth(a, beg1, b, beg2+i, k-i);
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
int m = nums2.size();
int k = (n+m) / 2 + 1;
int x = find_kth(nums1, 0, nums2, 0, k);
if((n + m) % 2 == 0)
return  (x + find_kth(nums1, 0, nums2, 0, k-1)) / 2.0;

return x;
}
};


参考资料:

一起爽leetcode(4)Median of Two Sorted Arrays
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: