leetcode 4(python实现)

本文介绍了如何用Python解决LeetCode第4题——找到两个有序数组的中位数。讨论了三种解法,包括归并排序、Python内置排序以及利用二分查找达到O(log(min(M,N)))的时间复杂度。同时,文章提到了时间复杂度和空间复杂度的概念,并列举了常见算法复杂度类型。" 103834684,2173775,Spring框架中的@RequestBody注解详解,"['Spring框架', 'Web开发', '注解', 'HTTP请求', 'JSON']
摘要由CSDN通过智能技术生成

leetcode 4

题目描述

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目解析
  • 思路一

看到这道题的第一反应就是用归并排序来做,将两个有序的数组首先合并为一个有序的数组,再返回这个有序数组的中位数,就是我们需要得到的结果。

但是,题目中还限制了一条,The overall run time complexity should be O(log (m+n)). 合并排序实现的代码提交时超出了时间限制,为什么会超出呢?我们先来分析一下我们的实现代码的时间复杂度

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        Key = []
        i = 0
        j = 0
        length1 = len(nums1)
        length2 = len(nums2)
        while (i < length1 and j < length2):
            if nums1[i] <= nums2[j]:
                Key.append(nums1[i])
                i = i + 1
            else:
                Key.append(nums2[j])
                j = j + 1
        while (i < length1):
            Key.append(nums1[i])
            i = i + 1
        while (j < length2):
            Key.append(nums2[j])
        length = len(Key)
        if length % 2 == 0:
            return (Key[length // 2] + Key[length // 2 - 1]) / 2
        else:
            return float(Key[length // 2])

输入的两个数组的长度分别为 m m m n n n,我们需要遍历两个数组,所以整体代码的时间复杂度为 O ( m + n ) O(m + n) O(m+n), 这显然不符合题目要求的时间复杂度

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值