Update Median of Two Sorted Arrays(Leetcode) #358
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When asked to find the median of two sorted arrays, a direct approach that merges the two arrays and then finds the median will work but isn't optimal. Given the problem's constraints, we can leverage the fact that the arrays are already sorted and use binary search to find the median in$O(\log(\min(n, m)))$ time complexity.
The key idea is to use binary search to partition the smaller array in such a way that we can easily find the median by comparing elements around the partition.
Detailed Explanation
Ensure the Smaller Array is First:
Set Up Binary Search:
Partitioning the Arrays:
where$x$ and $y$ are the lengths of $\text{nums1}$ and $\text{nums2}$ respectively.
Boundary Conditions:
Check Valid Partition:
A valid partition is one where the maximum element on the left side of both partitions is less than or equal to the minimum element on the right side of both partitions:
Here,$\text{maxX}$ is the largest element on the left side of $\text{nums1}$ , $\text{minX}$ is the smallest element on the right side of $\text{nums1}$ , and similarly for $\text{nums2}$ .
Calculate the Median:
Adjust Binary Search: