Lintcode 两个排序数组的中位数
2017-04-07 20:09
387 查看
两个排序的数组A和B分别含有m和n个数,找到两个排序数组的中位数,要求时间复杂度应为O(log (m+n))。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出数组A = [1,2,3,4,5,6] B = [2,3,4,5],中位数3.5
给出数组A = [1,2,3] B = [4,5],中位数 3
挑战
时间复杂度为O(log n)
标签
排序数组 分治法 数组 Zenefits 优步 谷歌
如有问题请留言。
如有帮助请顶一个,你们的支持是我最大的动力。
文章均可以转载,但请注明文章链接,谢谢。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出数组A = [1,2,3,4,5,6] B = [2,3,4,5],中位数3.5
给出数组A = [1,2,3] B = [4,5],中位数 3
挑战
时间复杂度为O(log n)
标签
排序数组 分治法 数组 Zenefits 优步 谷歌
class Solution { public: /** * @param A: An integer array. * @param B: An integer array. * @return: a double whose format is *.5 or *.0 */ double findMedianSortedArrays(vector<int> A, vector<int> B) { //int minidx = 0, maxidx = m, i, j, num1, mid = (m + n + 1) >> 1,num2; if (A.size() > B.size()) return findMedianSortedArrays(B,A); int m = A.size(),n = B.size(); int imin = 0,imax = m,half_len = (m + n + 1) / 2,i,j,max_of_left,min_of_right; while (imin <= imax) { i = (imin + imax) / 2; j = half_len - i; if (i < m && j > 0 && B[j - 1] > A[i]) imin = i + 1; else if (i > 0 && j < n && B[j] < A[i - 1]) imax = i - 1; else { if (i == 0) max_of_left = B[j - 1]; else if (j == 0) max_of_left = A[i - 1]; else max_of_left = max(A[i - 1],B[j - 1]); break; } } if ((m + n) % 2 == 1) return max_of_left; if (i == m) min_of_right = B[j]; else if (j == n) min_of_right = A[i]; else min_of_right = min(A[i],B[j]); return (max_of_left + min_of_right) / 2.0; } };
如有问题请留言。
如有帮助请顶一个,你们的支持是我最大的动力。
文章均可以转载,但请注明文章链接,谢谢。
相关文章推荐
- #google面试题14#找出两个排序数组的合并后的中位数
- 给两个排序好的数组,怎么求两个数组合并后的中位数?
- LintCode Remove Duplicates from Sorted Array II 删除排序数组中的重复数字 II
- LintCode 寻找旋转排序数组中的最小值
- lintcode-搜索旋转排序数组-62
- 两个排序数组的中位数
- leetcode Median of Two Sorted Arrays java 两个排序数组的中位数
- LintCode Merge Sorted ArrayII 合并排序数组 II
- 【LeetCode】004 Median of Two Sorted Arrays 两个排序数组合并后的中位数
- LintCode 删除排序数组中的重复数字
- 【转载】两个排序数组的中位数 / 第K大元素(Median of Two Sorted Arrays)
- 找两个排序数组的中位数
- 用O(lgn)时间求出两个已排序数组的中位数
- 【LeetCode-面试算法经典-Java实现】【004-Median of Two Sorted Arrays(两个排序数组的中位数)】
- 两个排序数组的中位数
- 求两个相同大小已排序数组中的中位数
- 2.Median of Two Sorted Arrays (两个排序数组的中位数)
- 求两个大小为n的已排序数组的中位数
- [LeetCode]4. Median of Two Sorted Arrays两个排序数组合并后的中位数
- Median of Two Sorted Arrays 求出两个已排序数组的中位数