16 May 2023 · filed under Coding challenge

LeetCode: Median of Two Sorted Arrays

pythonleetcodesorting

Solution #1

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

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