4.Median-of-Two-Sorted-Arrays
4. Median of Two Sorted Arrays
题目地址
https://leetcode.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代码
Approach 1: Merge sort with equal length
Approach #2 space optimization
Approach #3 归并排序
题中已有信息两个数组均为有序,找中位数的关键在于找到第一半大的数,显然可以使用二分搜索优化。本题是找中位数,其实可以泛化为一般的找第 k 大数,这个辅助方法的实现非常有意义!在两个数组中找第k大数->找中位数即为找第k大数的一个特殊情况——第(A.length + B.length) / 2 大数。因此首先需要解决找第k大数的问题。这个联想确实有点牵强...
由于是找第k大数(从1开始),使用二分法则需要比较A[k/2 - 1]和B[k/2 - 1],并思考这两个元素和第k大元素的关系。
A[k/2 - 1] <= B[k/2 - 1] => A和B合并后的第k大数中必包含A[0]~A[k/2 -1],可使用归并的思想去理解。
若k/2 - 1超出A的长度,则必取B[0]~B[k/2 - 1]
Last updated
Was this helpful?