LeetCode004__Median of Two Sorted Arrays

国际惯例:
here 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

分情况,1、数组元素个数为偶数;2、数组元素个数为奇数
为偶数时需要找到两个元素(x,y)取平均值,为奇数则取出中间数(x);
那么,要使得时间消耗为O(log(m+n))就需要进行二分查找法,两个数组同时从中间开始查找,寻找出在所有元素中第x,y位或者第x位元素。
需要用到递归了……
尴尬了,递归写不出来。。。
那么换一种思路吧,二分查找怎么样,毕竟python的list可变长度,不怕溢出,随意来插入。。。
不多说,贴代码:

import bisect
class Solution(object):

        def mainFunc(self,nums):
            s=len(nums)
            if s%2==0:
                return float(nums[s/2]+nums[s/2-1])/2
            else:
                return nums[s/2]

        def findMedianSortedArrays(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: float
            """
            l1=len(nums1)
            l2=len(nums2)
            if l1==l2==0:
                return 0
            elif l1==0:
                return self.mainFunc(nums2)
            elif l2==0:
                return self.mainFunc(nums1)

            elif l1>l2:
                result=nums1
                for i in xrange(l2):
                    index=bisect.bisect_left(result,nums2[i])
                    result.insert(index,nums2[i])
                return self.mainFunc(result)
            else:
                result=nums2
                for i in xrange(l1):
                    index=bisect.bisect_left(result,nums1[i])
                    result.insert(index,nums1[i])
                return self.mainFunc(result)

搞定收工!
第二个full persent!
我估计python这种语言就应该多用库,好多自己写递归的时间效率反而不如我这个。。。汗颜啊这里写图片描述

再来回顾一下,虽然运行时间短,但是那是因为python库函数处理效率高,本算法的实际运行时间是O(min(m,n)),并没有达到题目要求的O(log(m+n)),所以从题目来看还是失败的,思想还是应该是递归。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值