- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 31 lines of Java from the credited upstream file 4.java.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public double findMedianSortedArrays(int[] nums1, int[] nums2) {3 final int n1 = nums1.length;4 final int n2 = nums2.length;5 if (n1 > n2)6 return findMedianSortedArrays(nums2, nums1);7 8 int l = 0;9 int r = n1;10 11 while (l <= r) {12 final int partition1 = (l + r) / 2;13 final int partition2 = (n1 + n2 + 1) / 2 - partition1;14 final int maxLeft1 = partition1 == 0 ? Integer.MIN_VALUE : nums1[partition1 - 1];15 final int maxLeft2 = partition2 == 0 ? Integer.MIN_VALUE : nums2[partition2 - 1];16 final int minRight1 = partition1 == n1 ? Integer.MAX_VALUE : nums1[partition1];17 final int minRight2 = partition2 == n2 ? Integer.MAX_VALUE : nums2[partition2];18 if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1)19 return (n1 + n2) % 2 == 020 ? (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) * 0.521 : Math.max(maxLeft1, maxLeft2);22 else if (maxLeft1 > minRight2)23 r = partition1 - 1;24 else25 l = partition1 + 1;26 }27 28 throw new IllegalArgumentException();29 }30}31