4. Median of Two Sorted Arrays
Hard
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:
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)。
将时间复杂度降为O(log(m+n)),对两个数组同时进行二分查找,逐步排除掉不可能出现中位数的区间,最后找到所求的中位数。
这种解法的主要思想就是:
将问题转化为两个有序序列找第num大的数,在时间复杂度为log(m+n)限定下,采用类似二分思想,每个步骤去掉一半数据元素。
如果数组a的中位数小于数组b的中位数,那么整体的中位数只可能出现在a的右区间加上b的左区间之中;
如果数组a的中位数大于等于数组b的中位数,那么整体的中位数只可能出现在a的左区间加上b的右区间之中。
关键就是利用分治的思想逐渐缩小a的区间和b的区间来找到中位数。
二分法Python代码
def bin_search(data_list, val): low = 0 # 最小数下标 high =plen(data_list) - 1 # 最大数下标 while low <= high: mid = (low + high) / 2 # 中间数下标 if data_list[mid] == val: # 如果中间数下标等于val,返回 return mid elif data_list[mid] > val: # 如果val在中间数左边,移动high下标 high = mid - 1 else: # 如果val在中间数右边,移动low下标 low = mid + 1 return None # val不存在,返回None ret = bin_search(list(range(1,10)), 3) print(ret)
C++:
Python:
No1示例:

浙公网安备 33010602011771号