Skip to main content

4. 寻找两个正序数组的中位数 [hard]

4. 寻找两个正序数组的中位数 [hard]

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

给定两个大小为 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

通过次数215,004 | 提交次数561,181

First Try

想不出来,随便用浑水摸鱼写法,复杂度是错的,但是竟然也能够通过。

还是不能算通过啊。

class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
"""
1. 查找中间重叠的部分
2. 一个个往上找?
3. 头疼..
"""
# 浑水摸鱼写法
newone = sorted(nums1 + nums2)
idx, rem = divmod(len(newone), 2)
if rem == 0:
return (newone[idx] + newone[idx-1]) / 2.0
return newone[idx]
  • 执行用时:3200 ms, 在所有 Python 提交中击败了37.75%的用户
  • 内存消耗:20.2 MB, 在所有 Python 提交中击败了8.70%的用户