LeetCode 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


思路:

看示例得知,中位数的概念是奇数情况:为中间位;偶数情况为中间2位之和平均数。

这个题目看起来没有什么难的,唯一要注意的地方就是,python 中的% 和/ 要弄懂意思。

%取余数,

/取整数,

如果除法运算想保留小数点,我这边的做法是乘以1.0在进行/整出运算,这样就会有完整结果。

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        tmp = []
        result = 0
        for i in nums1:
            tmp.append(i)
        for n in nums2:
            tmp.append(n)
        tmp.sort() #排序
        p = len(tmp)%2
        if p ==0: #偶数
            result = (tmp[len(tmp)/2-1]+tmp[len(tmp)/2])*1.0/2 #/在python中地板除,也就是说取整,如果想保留小数精度,那就得乘以1.0
        else: #奇数
            result = tmp[(len(tmp)+1)/2-1]
        return result

执行用时 :48 ms, 在所有 Python 提交中击败了76.69%的用户

内存消耗 :12.8 MB, 在所有 Python 提交中击败了11.11%的用户

猜你喜欢

转载自www.cnblogs.com/xiaoqiangink/p/12920570.html
今日推荐