
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).
1public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
2 if (nums1.Length > nums2.Length) {
3 return FindMedianSortedArrays(nums2, nums1);
4 }
5 int x = nums1.Length;
6 int y = nums2.Length;
7 int low = 0, high = x;
8 while (low <= high) {
9 int partitionX = (low + high) / 2;
10 int partitionY = (x + y + 1) / 2 - partitionX;
11 int maxX = (partitionX == 0) ? int.MinValue : nums1[partitionX - 1];
12 int minX = (partitionX == x) ? int.MaxValue : nums1[partitionX];
13 int maxY = (partitionY == 0) ? int.MinValue : nums2[partitionY - 1];
14 int minY = (partitionY == y) ? int.MaxValue : nums2[partitionY];
15 if (maxX <= minY && maxY <= minX) {
16 if ((x + y) % 2 == 0) {
17 return ((double)Math.Max(maxX, maxY) + Math.Min(minX, minY)) / 2;
18 } else {
19 return (double)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 ArgumentException("Input arrays are not sorted.");
28}C# follows closely with C++ and Java with well-defined partitions and similar boundary handling with int.MinValue and int.MaxValue. The process ensures efficient convergence to the correct median calculation.
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.