Created
July 13, 2014 05:13
-
-
Save adohe-zz/c00b7733de44fc8a0ced to your computer and use it in GitHub Desktop.
Find the median or k-th element of two sorted arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.ado.java; | |
| public class LeetCodeFive { | |
| private static double findMedianOfSortedArray(int[] a, int[] b) { | |
| int m = a.length; | |
| int n = b.length; | |
| if ((m + n) % 2 == 0) { | |
| // even | |
| return (findKthElement(a, b, (m + n)/2, 0, m -1, 0, n - 1) + | |
| findKthElement(a, b, (m + n)/2 -1, 0, m - 1, 0, n -1)) * 0.5; | |
| } else { | |
| // odd | |
| return findKthElement(a, b, (m + n)/2, 0, m - 1, 0, n - 1); | |
| } | |
| } | |
| private static int findKthElement(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 a[aStart] < b[bStart] ? 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 - (aMid - aStart + 1); | |
| bEnd = bMid; | |
| aStart = aMid + 1; | |
| } else { | |
| k = k - (bMid - bStart + 1); | |
| aEnd = aMid; | |
| bStart = bMid + 1; | |
| } | |
| return findKthElement(a, b, k, aStart, aEnd, bStart, bEnd); | |
| } | |
| public static void main(String[] args) { | |
| int[] a = new int[]{1, 3, 6, 8, 10}; | |
| int[] b = new int[]{2, 4, 5, 7}; | |
| System.out.println(findMedianOfSortedArray(a, b)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment