lintcode, 两个排序数组的中位数
2016-11-29 19:57
435 查看
两个排序的数组A和B分别含有m和n个数,找到两个排序数组的中位数,要求时间复杂度应为O(log (m+n))。
给出数组A = [1,2,3,4,5,6] B = [2,3,4,5],中位数3.5
给出数组A = [1,2,3] B = [4,5],中位数 3
解题思路:需要满足时间复杂度为logn,结合findkth的思路,每次判断A和B在k/2位置的大小关系,然后舍弃数组中的部分数字,不断二分。找到一个具体的分析在下面的链接里
http://www.cnblogs.com/yuzhangcmu/p/4138184.html
一刷没有ac
二刷没有ac
给出数组A = [1,2,3,4,5,6] B = [2,3,4,5],中位数3.5
给出数组A = [1,2,3] B = [4,5],中位数 3
解题思路:需要满足时间复杂度为logn,结合findkth的思路,每次判断A和B在k/2位置的大小关系,然后舍弃数组中的部分数字,不断二分。找到一个具体的分析在下面的链接里
http://www.cnblogs.com/yuzhangcmu/p/4138184.html
一刷没有ac
二刷没有ac
class Solution { /** * @param A: An integer array. * @param B: An integer array. * @return: a double whose format is *.5 or *.0 */ public double findMedianSortedArrays(int[] A, int[] B) { if (A == null && B == null) return 0; int len = A.length + B.length; if (len % 2 == 0){ return (findKth(A, 0, B, 0, len/2) + findKth(A, 0, B, 0, len/2 + 1)) / 2.0; } return findKth(A, 0, B, 0, len/2+1); } public static double findKth(int[] A, int startA, int[] B, int startB, int k){ if (startA >= A.length){ return B[startB + k - 1]; } if (startB >= B.length){ return A[startA + k - 1]; } if (k == 1){ return Math.min(A[startA], B[startB]); } int keyA = startA + k / 2 - 1 < A.length ? A[startA + k / 2 - 1] : Integer.MAX_VALUE; int keyB = startB + k / 2 - 1 < B.length ? B[startB + k / 2 - 1] : Integer.MAX_VALUE; if (keyA < keyB){ return findKth(A, startA + k / 2, B, startB, k - k / 2); } return findKth(A, startA, B, startB + k / 2, k - k / 2); } }
相关文章推荐
- [LintCode] 两个排序数组的中位数
- LintCode 两个排序数组的中位数
- lintcode-65-两个排序数组的中位数
- leetcode Median of Two Sorted Arrays java 两个排序数组的中位数
- 两个排序数组的中位数
- leetcode题目 寻找两个排序数组的中位数
- 用O(lgn)时间求出两个已排序数组的中位数
- 【转载】两个排序数组的中位数 / 第K大元素(Median of Two Sorted Arrays)
- Arithmetic problem | 求两个排序数组的中位数
- [leetcode] Median of Two Sorted Arrays 两个排序数组找出第k个数,或者中位数
- [LeetCode]4. Median of Two Sorted Arrays两个排序数组合并后的中位数
- #google面试题14#找出两个排序数组的合并后的中位数
- 两个排序数组的中位数
- 利用分治法来求两个排序数组的中位数
- 找出两个排序数组的中位数
- Median of Two Sorted Arrays 求出两个已排序数组的中位数
- 给两个排序好的数组,怎么求两个数组合并后的中位数?
- 求两个相同大小已排序数组中的中位数
- 2.Median of Two Sorted Arrays (两个排序数组的中位数)
- 求两个大小为n的已排序数组的中位数