Intuition
Merge both sorted arrays into one sorted array using the merge step of merge sort, then directly pick the median from the middle.
Explanation
Brute Force
Use two pointers to merge both sorted arrays into a single sorted array. Then find the median: if the total length is odd, return the middle element; if even, return the average of the two middle elements.
Merging takes O(m+n) time and O(m+n) space. This is straightforward but does not achieve the O(log(m+n)) time that the problem ideally requires.
Why it is slow: We process every element when we only need to find the middle value.
Implementation
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] merged = new int[nums1.length + nums2.length];
int i = 0, j = 0, k = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] <= nums2[j]) {
merged[k++] = nums1[i++];
} else {
merged[k++] = nums2[j++];
}
}
while (i < nums1.length) merged[k++] = nums1[i++];
while (j < nums2.length) merged[k++] = nums2[j++];
int total = merged.length;
if (total % 2 == 1) {
return merged[total / 2];
} else {
return (merged[total / 2 - 1] + merged[total / 2]) / 2.0;
}
}
}