Leetcode 4. Median of Two Sorted Arrays The Solution of Python

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)).

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

Python 1:

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        nums1=sorted(nums1+nums2)#组合并排序
        return nums1[len(nums1)/2] if len(nums1)%2==1 else float(nums1[len(nums1)/2-1]+nums1[len(nums1)/2])/2#返回中值

Python 2:

import sys
class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        if len(nums1)<len(nums2):
            nums1,nums2=nums2,nums1
        a,b=0,len(nums2)*2
        while a<=b:
            mid2=(a+b)/2
            mid1=len(nums1)+len(nums2)-mid2
            L1=nums1[(mid1-1)/2] if mid1!=0 else -sys.maxint-1
            L2=nums2[(mid2-1)/2] if mid2!=0 else -sys.maxint-1
            R1=nums1[(mid1)/2] if mid1!=len(nums1)*2 else sys.maxint
            R2=nums2[(mid2)/2] if mid2!=len(nums2)*2 else sys.maxint
            if L1>R2:
                a=mid2+1
            elif L2>R1:
                b=mid2-1
            else:
                return float(max(L1,L2)+min(R1,R2))/2

题目要求时间复杂度不大于O(log (m+n)),因此第一种解决方案不能满足题目要求,但是代码和思想比较简单。第二种解决方案以二分查找为主要思想,通过找到两个list中的切分值,使其满足切分线左边的值小于右边的值,得到中值。
附上某不知名大神的详细解释(C++)

https://discuss.leetcode.com/topic/16797/very-concise-o-log-min-m-n-iterative-solution-with-detailed-explanation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值