4. 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)).
Example 1:1234nums1 = [1, 3]nums2 = [2]The median is 2.0
Example 2:1234nums1 = [1, 2]nums2 = [3, 4]The median is (2 + 3)/2 = 2.5
这个题目一看要求的时间复杂度为O(long(m+n)),基本说明这个题目要用二分法来做。
该题的做法可以解决所有求有序数组A和B有序合并之后第k小的数!
该题的重要结论:
如果A[k/2 - 1] < B[k/2 - 1]
,那么所求第k小一定不在 A[0] ~ A[k/2 - 1] 中。
代码来自九章算法:
|
|