1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { if (nums1.length > nums2.length) { return findMedianSortedArrays(nums2, nums1); }
int expectedNums1LeftSize = (nums1.length + nums2.length) / 2; int left = 0, right = nums1.length;
while (left <= right) { int nums1SubSize = (left + right) >>> 1, nums2SubSize = expectedNums1LeftSize - nums1SubSize;
int nums1LeftBoundary = nums1SubSize == 0 ? Integer.MIN_VALUE : nums1[nums1SubSize - 1]; int nums1RightBoundary = nums1SubSize == nums1.length ? Integer.MAX_VALUE : nums1[nums1SubSize]; int nums2LeftBoundary = nums2SubSize == 0 ? Integer.MIN_VALUE : nums2[nums2SubSize - 1]; int nums2RightBoundary = nums2SubSize == nums2.length ? Integer.MAX_VALUE : nums2[nums2SubSize];
if (nums1LeftBoundary > nums2RightBoundary) { right = nums1SubSize - 1; } else if (nums2LeftBoundary > nums1RightBoundary) { left = nums1SubSize + 1; } else { int totalSize = nums1.length + nums2.length;
boolean odd = ((totalSize) & 1) == 1; int leftMax = Math.max(nums1LeftBoundary, nums2LeftBoundary); int rightMin = Math.min(nums1RightBoundary, nums2RightBoundary); if (odd) { return rightMin; } else { return (leftMax + rightMin) / 2.0; } } }
return 0; } }
|
References
4. Median of Two Sorted Arrays