Leet Code 4 求两个有序数组的中位数 - Java
2016-06-05 00:00
447 查看
摘要: Leet Code 4 Median of Two Sorted Arrays - 求两个有序数组的中位数 - Java
问题原始链接 https://leetcode.com/problems/median-of-two-sorted-arrays
有两个有序数组,大小分别为m和n,求这两个数组的中位数,时间复杂度需要是O(log(m+n))。
问题原始链接 https://leetcode.com/problems/median-of-two-sorted-arrays
有两个有序数组,大小分别为m和n,求这两个数组的中位数,时间复杂度需要是O(log(m+n))。
[code=language-java]public class Solution { public static double findMedianSortedArrays(int A[], int B[]) { int m = A.length; int n = B.length; if ((m + n) % 2 != 0) { // 两个数组的元素总个数为奇数 return (double) findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1); } else { // 两个数组的元素总个数为偶数 return (findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1) + findKth(A, B, (m + n) / 2 - 1, 0, m - 1, 0, n - 1)) * 0.5; } } public static int findKth(int A[], int B[], int k, int aStart, int aEnd, int bStart, int bEnd) { int aLen = aEnd - aStart + 1; int bLen = bEnd - bStart + 1; if (aLen == 0) { return B[bStart + k]; } if (bLen == 0) { return A[aStart + k]; } if (k == 0) { return Math.min(A[aStart], B[bStart]); } int aMid = aLen * k / (aLen + bLen); int bMid = k - aMid - 1; aMid = aMid + aStart; bMid = bMid + bStart; if (A[aMid] > B[bMid]) { k = k - (bMid - bStart + 1); aEnd = aMid; bStart = bMid + 1; } else { k = k - (aMid - aStart + 1); bEnd = bMid; aStart = aMid + 1; } return findKth(A, B, k, aStart, aEnd, bStart, bEnd); } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解