impl Solution {
pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {
let (nums1, nums2) = if nums1.len() > nums2.len() {
(nums2, nums1)
} else {
(nums1, nums2)
}; // Ensure nums1 is the smaller array
let (m, n) = (nums1.len(), nums2.len()); // Get the lengths of the two arrays
let mut imin = 0; // Start of the binary search range
let mut imax = m; // End of the binary search range
let half_len = (m + n + 1) / 2; // Middle point of the combined arrays
while imin <= imax {
let i = (imin + imax) / 2; // Middle point of the binary search range
let j = half_len - i; // Corresponding point in the larger array
if i < m && nums2[j - 1] > nums1[i] {
// nums1's element is too small, increase the search range
imin = i + 1;
} else if i > 0 && nums1[i - 1] > nums2[j] {
// nums1's element is too large, decrease the search range
imax = i - 1;
} else {
// Correct partition found
let max_of_left = if i == 0 {
nums2[j - 1]
}
// Edge case: partition is at the start of nums1
else if j == 0 {
nums1[i - 1]
}
// Edge case: partition is at the start of nums2
else {
nums1[i - 1].max(nums2[j - 1])
}; // General case: max of the last elements in the left halves
if (m + n) % 2 == 1 {
return max_of_left as f64;
} // If total length is odd, return max of left elements
let min_of_right = if i == m {
nums2[j]
}
// Edge case: partition is at the end of nums1
else if j == n {
nums1[i]
}
// Edge case: partition is at the end of nums2
else {
nums1[i].min(nums2[j])
}; // General case: min of the first elements in the right halves
return (max_of_left + min_of_right) as f64 / 2.0; // If total length is even, return average of max of left and min of right elements
}
}
0.0 // Return 0.0 if no solution found (should not happen for valid input)
}
}