
Sponsored
Sponsored
This approach leverages binary search to reduce the problem to a smaller size, achieving the desired O(log(m + n)) complexity. The strategy involves performing binary search on the smaller array to find the perfect partition point.
Time complexity: O(log(min(m,n))). Space complexity: O(1).
1#include <stdio.h>
2#include <stdlib.h>
3#include <limits.h>
4
5double findMedianSortedArrays(int* nums1, int m, int* nums2, int n) {
6 if (m > n) {
7 return findMedianSortedArrays(nums2, n, nums1, m);
8 }
9 int imin = 0, imax = m, halfLen = (m + n + 1) / 2;
10 while (imin <= imax) {
11 int i = (imin + imax) / 2;
12 int j = halfLen - i;
13 if (i < m && nums2[j - 1] > nums1[i]) {
14 imin = i + 1;
15 } else if (i > 0 && nums1[i - 1] > nums2[j]) {
16 imax = i - 1;
17 } else {
18 int maxLeft = 0;
19 if (i == 0) { maxLeft = nums2[j - 1]; }
20 else if (j == 0) { maxLeft = nums1[i - 1]; }
21 else { maxLeft = (nums1[i - 1] > nums2[j - 1]) ? nums1[i - 1] : nums2[j - 1]; }
22 if ((m + n) % 2 == 1) {
23 return maxLeft;
24 }
25 int minRight = 0;
26 if (i == m) { minRight = nums2[j]; }
27 else if (j == n) { minRight = nums1[i]; }
28 else { minRight = (nums1[i] < nums2[j]) ? nums1[i] : nums2[j]; }
29 return (maxLeft + minRight) / 2.0;
30 }
31 }
32 return 0.0;
33}In this C solution, we first ensure that we perform the binary search on the smaller of the two arrays to maintain efficiency. We set bounds for `i` and adjust those bounds based on comparisons calculated at each step. The correct partitioning of elements between the two arrays determines the median.
This approach focuses on merging the two sorted arrays as naturally done in merge sort, and then finding the median directly from the merged result. Though this solution has a higher time complexity, it's easier to implement and understand.
Time complexity: O(m + n). Space complexity: O(m + n).
1def findMedianSortedArraysThe straightforward Python approach appends both arrays together and sorts them. It finds the median by selecting the middle element(s), depending on the total array length's parity.