LeetCode(No.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

思路:先合并,然后排序,再根据下标找到中间值

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

https://www.jianshu.com/p/6eab8e87a9de

猜你喜欢

转载自blog.csdn.net/zuolixiangfisher/article/details/88749456
今日推荐