- 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
- 32 lines of C++ from the credited upstream file 4.cpp.
- 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:3 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {4 const int n1 = nums1.size();5 const int n2 = nums2.size();6 if (n1 > n2)7 return findMedianSortedArrays(nums2, nums1);8 9 int l = 0;10 int r = n1;11 12 while (l <= r) {13 const int partition1 = (l + r) / 2;14 const int partition2 = (n1 + n2 + 1) / 2 - partition1;15 const int maxLeft1 = partition1 == 0 ? INT_MIN : nums1[partition1 - 1];16 const int maxLeft2 = partition2 == 0 ? INT_MIN : nums2[partition2 - 1];17 const int minRight1 = partition1 == n1 ? INT_MAX : nums1[partition1];18 const int minRight2 = partition2 == n2 ? INT_MAX : nums2[partition2];19 if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1)20 return (n1 + n2) % 2 == 021 ? (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.522 : max(maxLeft1, maxLeft2);23 else if (maxLeft1 > minRight2)24 r = partition1 - 1;25 else26 l = partition1 + 1;27 }28 29 throw;30 }31};32