/** * 4. Median of Two Sorted Arrays * <p> * Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. * <p> * The overall run time complexity should be O(log (m+n)). * <p> * Example 1: * <p> * Input: nums1 = [1,3], nums2 = [2] * Output: 2.00000 * Explanation: merged array = [1,2,3] and median is 2. * Example 2: * <p> * Input: nums1 = [1,2], nums2 = [3,4] * Output: 2.50000 * Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. * Example 3: * <p> * Input: nums1 = [0,0], nums2 = [0,0] * Output: 0.00000 * Example 4: * <p> * Input: nums1 = [], nums2 = [1] * Output: 1.00000 * Example 5: * <p> * Input: nums1 = [2], nums2 = [] * Output: 2.00000 * <p> * <p> * Constraints: * <p> * nums1.length == m * nums2.length == n * 0 <= m <= 1000 * 0 <= n <= 1000 * 1 <= m + n <= 2000 * -106 <= nums1[i], nums2[i] <= 106 */public class Lesson4 { public static void main(String[] args) { int[] nums1 = {1, 2}; int[] nums2 = {3, 4}; Util.println(new Solution().process(nums1, nums2)); //System.out.println(new Solution().process(nums1, nums2)); } private static class Solution { double process(int[] array1, int[] array2) { int[] arrayM = array1; int[] arrayN = array2; if (array1.length > array2.length) { arrayM = array2; arrayN = array1; } int m = arrayM.length; int n = arrayN.length; int min = 0; int max = m; int half = (m >> 1) + (n >> 1); while (min <= max) { int i = (min >> 1) + (max >> 1); int j = half - i; if (min < i && arrayM[i] < arrayN[j - 1]) { min = i + 1; } else if (i > min && arrayM[i - 1] > arrayN[j]) { max = i - 1; } else { int maxLeft = 0; if (i == 0) { maxLeft = arrayN[j - 1]; } else if (j == 0) { maxLeft = arrayM[i - 1]; } else { maxLeft = Math.max(arrayN[j - 1], arrayM[i - 1]); } if ((m + n) / 2 == 1) { return maxLeft + 0.0; } int minRight = 0; if (i == m) { minRight = arrayN[j]; } else if (j == n) { minRight = arrayM[i]; } else { minRight = Math.min(arrayN[j], arrayM[i]); } return (maxLeft + minRight) / 2.0; } } return 0.0; } }}