LeetCode 4. 寻找两个有序数组的中位数

4. 寻找两个有序数组的中位数

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。


示例1

nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0

示例2

nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5

解题思路
首先将两个List合并;然后将其排序;再判断长度的奇偶,若是奇数,则取中间一个数;反之,则取中间两数的平均值。


代码实现

class Solution:
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        nums = nums1 + nums2
        length = len(nums)
        nums.sort()
        if length % 2 == 0:
            index1 = length //2 -1 
            index2 = index1 + 1
            return (nums[index1] + nums[index2]) /2
        else:
            index = length//2
            return nums[index]

执行用时: 108 ms, 在Median of Two Sorted Arrays的Python3提交中击败了96.81% 的用户

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容