Leetcode_4. Median of Two Sorted Arrays 求两个有序数组的中位数

本文介绍了一种寻找两个有序数组中位数的非递归算法,通过合并两个数组并利用排序后的数组找到中位数,满足O(log(m+n))的时间复杂度要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

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

代码:非递归思想,网站上提供的递归方法看不懂,本文用的方法时间复杂度满足要求,但是需要额外的内存开销。

思路很简单:遍历两个数组,按从小到大的顺序存在一个新数组中,遍历到第(m+n)/2个的时候停止,根据m+n是奇数还是偶数来从新数组中取出最后一个数,或者倒数两个数来计算中位数。

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        m, n = len(nums1), len(nums2)
        count = 0    #记录已经合并的数组元素的个数
        middle_index = (m+n)/2    #中间数字的下标
        sort_num = []    #存储排序后的数字

        i = j = 0     #分别遍历两个数组

        while count <= middle_index :
            if i < m and j < n :
                if nums1[i] <= nums2[j] :
                    sort_num.append(nums1[i])
                    i += 1                    
                else :
                    sort_num.append(nums2[j])
                    j += 1                 
            elif i < m :
                sort_num.append(nums1[i])
                i += 1  
            elif j < n :
                sort_num.append(nums2[j])
                j += 1
            count += 1

        if (m+n)%2 == 1 :
            return (sort_num[count-1]+sort_num[count-1])/2.0
        else :
            if m+n == 0 :
                return "nums1 and nums2 are empty!"
            else :
                return (sort_num[count-1]+sort_num[count-2])/2.0

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值