博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 4. Median of Two Sorted Arrays_Hard tag: Array, Binary Search
阅读量:4585 次
发布时间:2019-06-09

本文共 1734 字,大约阅读时间需要 5 分钟。

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

这个题目我们可以用O(m + n) , 也就是two pointers去得到medium。

但是我们还可以利用divide and conquer的做法,并且更general 去求nums1,nums2中第k个大的值,然后将总长度是奇数和偶数分开来讨论,即可。

T: O(lg(m + n))

关于求nums1,nums2中第k个大的值,我们去比较nums1[start1 + k//2 - 1], nums2[start2 + k//2 - 1] 的值,如果某一个比较小,表明第k大的肯定不在那个数组的前k//2个,可以将其舍去,有点想二分法,只不过是在两个数组之间进行比较,注意的是如果start1 + k//2 - 1 > length, 那么我们就将其设为maxValue = max(nums1[-1], nums2[-1]) + 1,因为肯定是要舍弃另一个数组中的前k//2个。

code

class Solution:    def medianTwoArray(self, nums1, nums2):        def findKth(nums1, start1, nums2, start2, k):            if start1 >= len(nums1):                return nums2[start2 + k - 1]            if start2 >= len(nums2):                return nums1[start1 + k - 1]            if k == 1:                return min(nums1[start1], nums[start2])            maxValue = max(nums1[-1], nums2[-1]) + 1            value1 = nums1[start1 + k//2 - 1] if start1 + k//2 - 1 < len(nums1) else maxValue            value2 = nums2[start2 + k//2 - 1] if start2 + k//2 - 1 < len(nums2) else maxValue            return findKth(nums1, start1 + k//2, nums2, start2, k - k//2) if value1 < value2 else findKth(nums1, start1, nums2, start2 + k//2, k - k//2)        total = len(nums1) + len(nums2)        return findKth(nums1, 0, nums2, 0, total//2) if total%2 else (findKth(nums1, 0, nums2, total//2) + findKth(nums1, 0, nums2, 0,total//2 + 1 ))/2

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/10843534.html

你可能感兴趣的文章
RTL基本知识:编译命令指定隐性线网类型
查看>>
java中BigDecimal在金融行业中的使用
查看>>
66.Plus One
查看>>
爬虫——小结
查看>>
sticky bit
查看>>
sqlserver 中 where 条件和 join 条件的作用比较
查看>>
jvm解析和调优
查看>>
Linux 连接mysql服务器
查看>>
linux内核学习:中断中推后执行的部分
查看>>
数据库系统概论【基础篇】
查看>>
shell脚本中大于,大于等于,小于,小于等于、不等于的表示方法
查看>>
xcode 快捷键
查看>>
三十五.MySQL读写分离 MySQL多实例 、MySQL性能调优
查看>>
[LeetCode] 256. Paint House_Easy tag: Dynamic Programming
查看>>
Java基础——面向对象编程一:封装
查看>>
python ==> Django.view(登录,注册,个人页)
查看>>
在maven中没有的jar包如何处理?
查看>>
多线程与UI操作
查看>>
python 打印三角行,金字塔等
查看>>
CSS3 3D下拉折叠菜单
查看>>