LeetCode 4. Median of Two Sorted Arrays Python3

LeetCode 4. Median of Two Sorted Arrays Python3

Description

点击查看题目
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

问题分析

刚开始看到这是一道 困难题,但是读完题后并没有发现有啥不理解的地方,题目的意思是给定两个有序数组,找出这两个数组的中位数,而且题目给出的example解释了啥是中位数,所以虽然题目给的标签是困难题,但是只要把两个有序数组进行合并,然后返回中位数即可。

最近在学Python,也不是说重头开始吧,因为之前学过C++、Java,就是按照之前学习过的思维模式去尝试用Python实现,然后再去看看别人用Python写的简洁、高效代码,所以有时候如果看不惯我写的代码,还望勿怪,不过我自己完成后都会去看评论区的代码,努力提高自己的编程能力,有兴趣的可以交流哦。

代码实现

第一种方法实现

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

第二种方法实现

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        length = len(nums1) + len(nums2)
        res = []
        while nums1 and nums2:
            res.append(nums1.pop(0) if nums1[0] < nums2[0] else nums2.pop(0))
        if nums1:
            res += nums1
        else:
            res += nums2
        if length % 2 == 0:
            result = (res[length // 2 - 1] + res[length // 2]) / 2.
        else:
            result = res[length // 2] * 1.
        return result

运行结果对比

在这里插入图片描述
从图中可以看出,运用Python封装好的方法运行起来还是比自己写的要高效的,所以要学会站在巨人的肩膀上,借助于外物,不要重复造轮子。

ok!大功告成了,如果你有其他的方法或者问题,欢迎在评论区交流。

发布了20 篇原创文章 · 获赞 28 · 访问量 6084

猜你喜欢

转载自blog.csdn.net/qq_38929464/article/details/104098326