|
| 1 | +import com.sun.tools.internal.ws.wsdl.document.soap.SOAPUse; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by gouthamvidyapradhan on 09/04/2017. |
| 5 | + */ |
| 6 | +public class MedianOfTwoSortedArrays |
| 7 | +{ |
| 8 | + /** |
| 9 | + * Main method |
| 10 | + * @param args |
| 11 | + * @throws Exception |
| 12 | + */ |
| 13 | + public static void main(String[] args) throws Exception |
| 14 | + { |
| 15 | + int[] A = {10}; |
| 16 | + int[] B = {12}; |
| 17 | + System.out.println(new MedianOfTwoSortedArrays().findMedianSortedArrays(A, B)); |
| 18 | + } |
| 19 | + |
| 20 | + public double findMedianSortedArrays(int A[], int B[]) { |
| 21 | + int n = A.length; |
| 22 | + int m = B.length; |
| 23 | + // the following call is to make sure len(A) <= len(B). |
| 24 | + // yes, it calls itself, but at most once, shouldn't be |
| 25 | + // consider a recursive solution |
| 26 | + if (n > m) |
| 27 | + return findMedianSortedArrays(B, A); |
| 28 | + |
| 29 | + // now, do binary search |
| 30 | + int k = (n + m - 1) / 2; |
| 31 | + int l = 0, r = Math.min(k, n); // r is n, NOT n-1, this is important!! |
| 32 | + while (l < r) { |
| 33 | + int midA = (l + r) / 2; |
| 34 | + int midB = k - midA; |
| 35 | + if (A[midA] < B[midB]) |
| 36 | + l = midA + 1; |
| 37 | + else |
| 38 | + r = midA; |
| 39 | + } |
| 40 | + |
| 41 | + // if (n+m) is odd, the median is the larger one between A[l-1] and B[k-l]. |
| 42 | + // and there are some corner cases we need to take care of. |
| 43 | + int a = Math.max(l > 0 ? A[l - 1] : Integer.MIN_VALUE, k - l >= 0 ? B[k - l] : Integer.MIN_VALUE); |
| 44 | + if (((n + m) & 1) == 1) |
| 45 | + return (double) a; |
| 46 | + |
| 47 | + // if (n+m) is even, the median can be calculated by |
| 48 | + // median = (max(A[l-1], B[k-l]) + min(A[l], B[k-l+1]) / 2.0 |
| 49 | + // also, there are some corner cases to take care of. |
| 50 | + int b = Math.min(l < n ? A[l] : Integer.MAX_VALUE, k - l + 1 < m ? B[k - l + 1] : Integer.MAX_VALUE); |
| 51 | + return (a + b) / 2.0; |
| 52 | + } |
| 53 | +} |
0 commit comments