Loading...
Loading...
You are given two sorted arrays nums1 and nums2 of sizes m and n respectively. Your task is to find the median of the two sorted arrays combined.
The median is the middle value in an ordered list. If the total number of elements is even, the median is the average of the two middle values.
nums1: A sorted integer array of length mnums2: A sorted integer array of length nInput: nums1 = [1, 3], nums2 = [2]
Output: 2.0
Explanation: Merged array = [1, 2, 3]. Median is the middle element: 2.
Input: nums1 = [1, 2], nums2 = [3, 4]
Output: 2.5
Explanation: Merged array = [1, 2, 3, 4]. Median = (2 + 3) / 2 = 2.5.
Input: nums1 = [], nums2 = [1]
Output: 1.0
Explanation: Only one array has elements. Median of [1] is 1.0.
Merge both arrays into a single sorted array, then compute the median directly. This is straightforward but not optimal.
The key insight is to partition both arrays such that:
Binary search on the smaller array to find the correct partition point. At a valid partition:
maxLeft1 <= minRight2maxLeft2 <= minRight1The median is then derived from the boundary elements of the partitions.
Think about:
0 <= m, n <= 1000 1 <= m + n <= 2000 -10^6 <= nums1[i], nums2[i] <= 10^6 At least one of the two arrays is non-empty