Interview 150
Median of Two Sorted Arrays
- Problem
- LC 4
- File
- interview150_LC4MedianTwoSortedArrays.java
- Path
- pkg5leetcode/interview150/interview150_LC4MedianTwoSortedArrays.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC4MedianTwoSortedArrays.java
- Approach
- Binary search smaller array partition; O(log min(n,m)).
- Complexity
- Time O(log(min(n,m))), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Median of Two Sorted Arrays | LC 45 * APPROACH: Binary search smaller array partition; O(log min(n,m)).6 * COMPLEXITY: Time O(log(min(n,m))), Space O(1)7 */8public class interview150_LC4MedianTwoSortedArrays {9 static double findMedianSortedArrays(int[] a, int[] b) {10 if (a.length > b.length) return findMedianSortedArrays(b, a);11 int n = a.length, m = b.length, lo = 0, hi = n;12 while (lo <= hi) {13 int i = (lo + hi) / 2, j = (n + m + 1) / 2 - i;14 int aLo = i == 0 ? Integer.MIN_VALUE : a[i - 1];15 int aHi = i == n ? Integer.MAX_VALUE : a[i];16 int bLo = j == 0 ? Integer.MIN_VALUE : b[j - 1];17 int bHi = j == m ? Integer.MAX_VALUE : b[j];18 if (aLo <= bHi && bLo <= aHi) {19 if ((n + m) % 2 == 0) return (Math.max(aLo, bLo) + Math.min(aHi, bHi)) / 2.0;20 return Math.max(aLo, bLo);21 }22 if (aLo > bHi) hi = i - 1;23 else lo = i + 1;24 }25 return 0;26 }27 28 public static void main(String[] args) {29 check(findMedianSortedArrays(new int[]{1, 3}, new int[]{2}) == 2.0, "case1");30 check(findMedianSortedArrays(new int[]{1, 2}, new int[]{3, 4}) == 2.5, "case2");31 System.out.println("all tests passed");32 }33 34 static void check(boolean cond, String name) {35 if (!cond) throw new AssertionError("FAILED: " + name);36 System.out.println(" PASS " + name);37 }38}