LeetCode 4 Median of Two Sorted Arrays

来源:互联网 发布:海量数据和数据港 编辑:程序博客网 时间:2024/06/09 15:21

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

Example 2:

nums1 = [1, 2]nums2 = [3, 4]The median is (2 + 3)/2 = 2.5

每次在A,B取前k/2个元素。有以下这些情况:

1).  A的元素个数不够k/2. 则我们可以丢弃B前k/2(因为此时A的所有元素+B前k/2的个数也不够k个,所以B的k/2肯定没有第k个元素)。反之亦然。

2). A[mid] < B[mid] (mid是k/2 -1)。这种情况下,我们可以丢弃A前k/2。

public double findMedianSortedArrays(int[] A, int[] B) {int len = A.length + B.length;if (len % 2 == 1)return findKey(A, B, 0, 0, len / 2 + 1);return (findKey(A, B, 0, 0, len / 2) + findKey(A, B, 0, 0,len / 2 + 1)) / 2.0;}public int findKey(int[] A, int[] B, int aStart, int bStart, int k) {if (aStart == A.length) return B[bStart + k - 1];if (bStart == B.length) return A[aStart + k - 1];if (k == 1) return Math.min(A[aStart], B[bStart]);int akey = aStart + k / 2 - 1 < A.length ? A[aStart + k / 2 - 1] : Integer.MAX_VALUE;int bkey = bStart + k / 2 - 1 < B.length ? B[bStart + k / 2 - 1] : Integer.MAX_VALUE;if (akey < bkey) return findKey(A, B, aStart + k / 2, bStart, k - k / 2);else return findKey(A, B, aStart, bStart + k / 2, k - k / 2);}


0 0
原创粉丝点击