Median of Two Sorted Arrays

There are two sorted arraysnums1andnums2of 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

分析

本质是利用二分法,中间的数字比较,然后丢一半。

比较a[k/2] b[k/2] 哪个小就不要前半段,把该数组的start移动,同时k-k/2

特殊情况:

  • a没数了, b没数了, 取剩下的数

  • ab里只剩一个数了,取小的

  • 数组不足k/2,设置为max。这样可以取另一个数组里的数。

medium所以K存在,否则K判断k是否比俩加起来都大

递归里的参数都在变,有极端情况

python

记得helper递归时候,要移动到下一位,不是留在中位。

Last updated

Was this helpful?