4. 寻找两个有序数组的中位数_Median of Two Sorted Arrays

Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

You may assume nums1 and nums2 cannot be both empty.

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。

请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1 和 nums2 不会同时为空。

题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

python3:

from typing import List

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        list_len1 = len(nums1)
        list_len2 = len(nums2)
        sum_len = list_len1 + list_len2
        mid_len = sum_len // 2
        
        if list_len1 == 0:
            if sum_len % 2 == 0:
                return (nums2[mid_len] + nums2[mid_len - 1]) / 2
            else:
                return nums2[mid_len]
        if list_len2 == 0:
            if sum_len % 2 == 0:
                return (nums1[mid_len] + nums1[mid_len - 1]) / 2
            else:
                return nums1[mid_len]
        
        count = 0
        i = 0
        j = 0
        now_val = 0
        last_val = 0
        
        while i < list_len1 or j < list_len2:
            last_val = now_val
            if i < list_len1 and ((j >= list_len2) or (j < list_len2 and nums1[i] <= nums2[j])):
                now_val = nums1[i]
                i = i + 1
            else:
                now_val = nums2[j]
                j = j + 1
            if count == mid_len:
                if sum_len % 2 == 0:
                    return (last_val + now_val) / 2
                else:
                    return now_val
            count = count + 1

你可能感兴趣的:(LeetCode学习)