[LeetCode] 4.Median of Two Sorted Arrays

题目内容

给定两个大小为 m 和 n 的有序数组 nums1和 nums2

请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1 和 nums2 不会同时为空。

https://leetcode-cn.com/problems/median-of-two-sorted-arrays/

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

You may assume nums1 and nums2 cannot be both empty.

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

 


题目思路

一种比较好想的思路就是我把两个字符串合体成一个,然后直接输出。不过另一种方式就是进行比对排序,因为两个序列都是已经排序好的。先确定要找的是第几个数字即可。因为上来就排序的话,其实中位值之后的是不需要排序的,造成了浪费。但是后来我看了一下,使用第一种方法的速度要远快于第二种,晕菜。。


程序代码

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        l1,l2=len(nums1),len(nums2)
        length=l1+l2
        flag=1
        if length%2==0:#是偶数
            flag=2
        find=length//2+1
        res=[]
        while nums1 or nums2:
            if nums1 and nums2:
                if nums1[0]<=nums2[0]:
                    res.append(nums1.pop(0))   
                else:
                    res.append(nums2.pop(0))               
            elif nums1:
                res.extend(nums1)
                break
            elif nums2:
                res.extend(nums2)
                break
            if len(res)==find:
                break
        if flag==1:
            return res[length//2]
        else:
            return (res[length//2]+res[length//2-1])/2.0

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值