|
| 1 | +/** |
| 2 | + * Resources: https://www.youtube.com/watch?v=lLFDQCDzfpI |
| 3 | + * https://www.geeksforgeeks.org/merge-two-sorted-arrays/ |
| 4 | + */ |
| 5 | +class Solution { |
| 6 | + public double findMedianSortedArrays(int[] nums1, int[] nums2) { |
| 7 | + // Ensure nums1 has the greater length |
| 8 | + if (nums1.length > nums2.length) { |
| 9 | + int [] tmp = nums1; |
| 10 | + nums1 = nums2; |
| 11 | + nums2 = tmp; |
| 12 | + } |
| 13 | + |
| 14 | + int lo = 0; |
| 15 | + int hi = nums1.length; |
| 16 | + int combinedLen = nums1.length + nums2.length; |
| 17 | + |
| 18 | + while (lo <= hi) { |
| 19 | + int partX = (lo + hi) / 2; |
| 20 | + int partY = (combinedLen + 1) / 2 - partX; |
| 21 | + |
| 22 | + int leftX = getMax(nums1, partX); |
| 23 | + int rightX = getMin(nums1, partX); |
| 24 | + |
| 25 | + int leftY = getMax(nums2, partY); |
| 26 | + int rightY = getMin(nums2, partY); |
| 27 | + |
| 28 | + if (leftX <= rightY && leftY <= rightX) { |
| 29 | + if (combinedLen % 2 == 0) { |
| 30 | + return (Math.max(leftX, leftY) + Math.min(rightX, rightY)) / 2.0; |
| 31 | + } |
| 32 | + return Math.max(leftX, leftY); |
| 33 | + } |
| 34 | + |
| 35 | + if (leftX > rightY) { |
| 36 | + hi = partX - 1; |
| 37 | + } else { |
| 38 | + lo = partX + 1; |
| 39 | + } |
| 40 | + |
| 41 | + } |
| 42 | + |
| 43 | + return -1; |
| 44 | + } |
| 45 | + |
| 46 | + private int getMax(int[] nums, int partition) { |
| 47 | + if (partition == 0) { |
| 48 | + return (int)Double.NEGATIVE_INFINITY; |
| 49 | + } else { |
| 50 | + return nums[partition - 1]; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private int getMin(int[] nums, int partition) { |
| 55 | + if (partition == nums.length) { |
| 56 | + return (int)Double.POSITIVE_INFINITY; |
| 57 | + } else { |
| 58 | + return nums[partition]; |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments