原题目
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
思路
分别对两个数组进行二分查找,找到其中位数进行比较,将中位数较小的数组选择其中位数到最后一个元素作为新数组,中位数较大的数组选择其第一个元素到中位数作为新数组。
第一遍解法
- 方法一:没能解决的问题:偶数数组的中位数怎么选择?
- 方法二:将两个数组合并为一个数组然后排序取中位数
# Runtime: 52 ms, faster than 99.62% of Python3
# Memory Usage: 13.3 MB, less than 5.11% of Python3
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
for i in range(len(nums2)):
nums1.append(nums2[i])
nums1 = sorted(nums1)
l = len(nums1)
if l % 2 == 0:
return (nums1[l//2] + nums1[l//2-1]) / 2
else:
return float(nums1[l//2])
网上好的解法
def median(A, B):
m, n = len(A), len(B)
if m > n:
A, B, m, n = B, A, n, m
if n == 0:
raise ValueError
imin, imax, half_len = 0, m, (m + n + 1) / 2
while imin <= imax:
i = (imin + imax) / 2
j = half_len - i
if i < m and B[j-1] > A[i]:
# i is too small, must increase it
imin = i + 1
elif i > 0 and A[i-1] > B[j]:
# i is too big, must decrease it
imax = i - 1
else:
# i is perfect
if i == 0: max_of_left = B[j-1]
elif j == 0: max_of_left = A[i-1]
else: max_of_left = max(A[i-1], B[j-1])
if (m + n) % 2 == 1:
return max_of_left
if i == m: min_of_right = B[j]
elif j == n: min_of_right = A[i]
else: min_of_right = min(A[i], B[j])
return (max_of_left + min_of_right) / 2.0
自己可以改进的地方
最简代码