
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).
1var findMedianSortedArrays = function(nums1, nums2) {
2 if (nums1.length > nums2.length) {
3 [nums1, nums2] = [nums2, nums1];
4 }
5 let x = nums1.length;
6 let y = nums2.length;
7 let low = 0, high = x;
8 while (low <= high) {
9 let partitionX = (low + high) >> 1;
10 let partitionY = (x + y + 1) >> 1 - partitionX;
11 let maxX = (partitionX === 0) ? -Infinity : nums1[partitionX - 1];
12 let minX = (partitionX === x) ? Infinity : nums1[partitionX];
13 let maxY = (partitionY === 0) ? -Infinity : nums2[partitionY - 1];
14 let minY = (partitionY === y) ? Infinity : nums2[partitionY];
15 if (maxX <= minY && maxY <= minX) {
16 if ((x + y) % 2 === 0) {
17 return ((Math.max(maxX, maxY) + Math.min(minX, minY)) / 2);
18 } else {
19 return Math.max(maxX, maxY);
20 }
21 } else if (maxX > minY) {
22 high = partitionX - 1;
23 } else {
24 low = partitionX + 1;
25 }
26 }
27 throw new Error('Input arrays are not sorted.');
28};JavaScript's `findMedianSortedArrays` similarly navigates the problem utilizing closures and loop constructs that obey the binary search strategy effectively. -Infinity and Infinity act as edge handlers for different partition conditions.
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).
1#
The C implementation uses an auxiliary array to merge the two sorted arrays into one. After merging, we calculate the median of the merged array based on its even or odd length. Memory allocation and deallocation are crucial to manage space efficiently.