LeetCode: Median of Two Sorted Arrays

Solution 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from typing import List
from heapq import merge
from math import floor, ceil

def findMedianSortedArrays(nums1: List[int], nums2: List[int]) -> float:
    """
    Finds the median of two sorted arrays.

    Args:
        nums1 (List[int]): The first sorted array.
        nums2 (List[int]): The second sorted array.

    Returns:
        float: The median value.

    Examples:
        >>> findMedianSortedArrays([1, 3], [2])
        2.0
        >>> findMedianSortedArrays([1, 2], [3, 4])
        2.5
    """
    merged = tuple(merge(nums1, nums2))
    index = (0.5 * len(merged)) + 0.5
    if (index).is_integer():
        return merged[int(index) - 1]
    else:
        median = (merged[floor(index - 1)] + merged[ceil(index - 1)]) / 2
        return median

Solution 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from typing import List
from math import floor, ceil

def findMedianSortedArrays(nums1: List[int], nums2: List[int]) -> float:
    """
    Finds the median of two sorted arrays.

    Args:
        nums1 (List[int]): The first sorted array.
        nums2 (List[int]): The second sorted array.

    Returns:
        float: The median value.

    Examples:
        >>> findMedianSortedArrays([1, 3], [2])
        2.0
        >>> findMedianSortedArrays([1, 2], [3, 4])
        2.5
    """
    merged = sorted([*nums1, *nums2])
    index = (0.5 * len(merged)) + 0.5
    if (index).is_integer():
        return merged[int(index) - 1]
    else:
        median = (merged[floor(index - 1)] + merged[ceil(index - 1)]) / 2
        return median
0%