|
| 1 | +""" |
| 2 | +https://www.enjoyalgorithms.com/blog/median-of-two-sorted-arrays |
| 3 | +""" |
| 4 | + |
| 5 | + |
| 6 | +def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float: |
| 7 | + """ |
| 8 | + Find the median of two arrays. |
| 9 | +
|
| 10 | + Args: |
| 11 | + nums1: The first array. |
| 12 | + nums2: The second array. |
| 13 | +
|
| 14 | + Returns: |
| 15 | + The median of the two arrays. |
| 16 | +
|
| 17 | + Examples: |
| 18 | + >>> find_median_sorted_arrays([1, 3], [2]) |
| 19 | + 2.0 |
| 20 | +
|
| 21 | + >>> find_median_sorted_arrays([1, 2], [3, 4]) |
| 22 | + 2.5 |
| 23 | +
|
| 24 | + >>> find_median_sorted_arrays([0, 0], [0, 0]) |
| 25 | + 0.0 |
| 26 | +
|
| 27 | + >>> find_median_sorted_arrays([], []) |
| 28 | + Traceback (most recent call last): |
| 29 | + ... |
| 30 | + ValueError: Both input arrays are empty. |
| 31 | +
|
| 32 | + >>> find_median_sorted_arrays([], [1]) |
| 33 | + 1.0 |
| 34 | +
|
| 35 | + >>> find_median_sorted_arrays([-1000], [1000]) |
| 36 | + 0.0 |
| 37 | +
|
| 38 | + >>> find_median_sorted_arrays([-1.1, -2.2], [-3.3, -4.4]) |
| 39 | + -2.75 |
| 40 | + """ |
| 41 | + if not nums1 and not nums2: |
| 42 | + raise ValueError("Both input arrays are empty.") |
| 43 | + |
| 44 | + # Merge the arrays into a single sorted array. |
| 45 | + merged = sorted(nums1 + nums2) |
| 46 | + total = len(merged) |
| 47 | + |
| 48 | + if total % 2 == 1: # If the total number of elements is odd |
| 49 | + return float(merged[total // 2]) # then return the middle element |
| 50 | + |
| 51 | + # If the total number of elements is even, calculate |
| 52 | + # the average of the two middle elements as the median. |
| 53 | + middle1 = merged[total // 2 - 1] |
| 54 | + middle2 = merged[total // 2] |
| 55 | + return (float(middle1) + float(middle2)) / 2.0 |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + import doctest |
| 60 | + |
| 61 | + doctest.testmod() |
0 commit comments