|
| 1 | +import com.sun.org.apache.regexp.internal.recompile; |
| 2 | + |
| 3 | +/** |
| 4 | + * There are two sorted arrays nums1 and nums2 of size m and n respectively. |
| 5 | + * Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). |
| 6 | + * <p> |
| 7 | + * Example 1: |
| 8 | + * nums1 = [1, 3] |
| 9 | + * nums2 = [2] |
| 10 | + * The median is 2.0 |
| 11 | + * <p> |
| 12 | + * Example 2: |
| 13 | + * nums1 = [1, 2] |
| 14 | + * nums2 = [3, 4] |
| 15 | + * The median is (2 + 3)/2 = 2.5 |
| 16 | + * <p> |
| 17 | + * Created by drfish on 04/05/2017. |
| 18 | + */ |
| 19 | +public class _004MedianOfTwoSortedArrays { |
| 20 | + public double findMedianSortedArrays(int[] nums1, int[] nums2) { |
| 21 | + int k1 = (nums1.length + nums2.length + 1) / 2; |
| 22 | + int k2 = (nums1.length + nums2.length + 2) / 2; |
| 23 | + return (findK(nums1, 0, nums2, 0, k1) + findK(nums1, 0, nums2, 0, k2)) / 2.0; |
| 24 | + } |
| 25 | + |
| 26 | + private double findK(int[] nums1, int start1, int[] nums2, int start2, int k) { |
| 27 | + if (start1 >= nums1.length) { |
| 28 | + return nums2[start2 + k - 1]; |
| 29 | + } |
| 30 | + if (start2 >= nums2.length) { |
| 31 | + return nums1[start1 + k - 1]; |
| 32 | + } |
| 33 | + if (k == 1) { |
| 34 | + return Math.min(nums1[start1], nums2[start2]); |
| 35 | + } |
| 36 | + int mid1 = Integer.MAX_VALUE; |
| 37 | + int mid2 = Integer.MAX_VALUE; |
| 38 | + if (start1 + k / 2 - 1 < nums1.length) { |
| 39 | + mid1 = nums1[start1 + k / 2 - 1]; |
| 40 | + } |
| 41 | + if (start2 + k / 2 - 1 < nums2.length) { |
| 42 | + mid2 = nums2[start2 + k / 2 - 1]; |
| 43 | + } |
| 44 | + if (mid1 < mid2) { |
| 45 | + return findK(nums1, start1 + k / 2, nums2, start2, k - k / 2); |
| 46 | + } else { |
| 47 | + return findK(nums1, start1, nums2, start2 + k / 2, k - k / 2); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments