|
| 1 | +package com.interview.binarysearch; |
| 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 | + * |
| 7 | + * Solution |
| 8 | + * Take minimum size of two array. Possible number of cuts are from 0 to m in m size array. |
| 9 | + * Try every cut in binary search way. When you cut first array at i then you cut second array at (m + n + 1)/2 - i |
| 10 | + * Now try to find the i where a[i-1] <= b[j] and b[j-1] <= a[i]. So this i is the answerr |
| 11 | + * |
| 12 | + * Time complexity is O(log(min(m,n)) |
| 13 | + * |
| 14 | + * https://leetcode.com/problems/median-of-two-sorted-arrays/ |
| 15 | + * https://discuss.leetcode.com/topic/4996/share-my-o-log-min-m-n-solution-with-explanation/4 |
| 16 | + */ |
| 17 | +public class MedianOfTwoSortedArrayOfDifferentLength { |
| 18 | + public double findMedianSortedArrays(int input1[], int input2[]) { |
| 19 | + if (input1.length > input2.length) { |
| 20 | + return findMedianSortedArrays(input2, input1); |
| 21 | + } |
| 22 | + if (input1.length == 0) { |
| 23 | + return getMedian(input2); |
| 24 | + } |
| 25 | + int m = input1.length; |
| 26 | + int n = input2.length; |
| 27 | + |
| 28 | + int low = 0; |
| 29 | + int high = m; |
| 30 | + while (low <= high) { |
| 31 | + int cut1 = (low + high)/2; |
| 32 | + int cut2 = (m + n + 1)/2 - cut1; |
| 33 | + |
| 34 | + int a1 = (cut1 == 0) ? Integer.MIN_VALUE : input1[cut1 - 1]; |
| 35 | + int a2 = (cut1 == m) ? Integer.MAX_VALUE : input1[cut1]; |
| 36 | + |
| 37 | + int b1 = (cut2 == 0) ? Integer.MIN_VALUE : input2[cut2 - 1]; |
| 38 | + int b2 = (cut2 == n) ? Integer.MAX_VALUE : input2[cut2]; |
| 39 | + |
| 40 | + if (a1 <= b2 && b1 <= a2) { |
| 41 | + if ((m + n) % 2 == 0) { |
| 42 | + return ((double)Math.max(a1, b1) + Math.min(a2, b2))/2; |
| 43 | + } else { |
| 44 | + return (double)Math.max(a1, b1); |
| 45 | + } |
| 46 | + } else if (a1 > b2) { |
| 47 | + high = cut1 - 1; |
| 48 | + } else { |
| 49 | + low = cut1 + 1; |
| 50 | + } |
| 51 | + } |
| 52 | + throw new IllegalArgumentException(); |
| 53 | + } |
| 54 | + |
| 55 | + private double getMedian(int arr[]){ |
| 56 | + if(arr.length % 2 == 0){ |
| 57 | + return ((double)arr[arr.length/2 - 1] + arr[arr.length/2])/2; |
| 58 | + } else { |
| 59 | + return arr[arr.length/2]; |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments