Problem
有两个排序的数组nums1和nums2分别为m和n。
找到两个排序数组的中位数。总运行时间复杂度应为O(log(m + n))。
您可以假设nums1和nums2 不能都为空。
例1:
nums1 = [1,3]
nums2 = [2]
中位数是2.0
例2:
nums1 = [1,2]
nums2 = [3,4]
中位数为(2 + 3)/ 2 = 2.5
Algorithmic thinking
方法1:递归方法
要解决这个问题,我们需要了解“中位数有什么用”。在统计中,中位数用于:
将一组分成两个相等长度的子集,一个子集总是大于另一个子集。
如果我们理解使用中位数来划分,我们非常接近答案。
Python code
solution 1
class Solution:
def findMedianSortedArrays(self, A, B):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
# n>=m
m, n = len(A),len(B)
if n<m:
A, B, m, n = B, A, n, m
imin, imax, halfLen = 0, m, (m+n+1)/2
while(imin <= imax):
i = int((imin+imax)/2)
j = int(halfLen)-i
if i > 0 and A[i-1] > B[j]:
imax = i - 1
elif i < m and A[i] < B[j-1]:
imin = i + 1
else:
# i is perfect
if i==0:
maxLeft = B[j-1]
elif j==0:
maxLeft = A[i-1]
else:
maxLeft = max(A[i-1], B[j-1])
if (m+n) % 2 == 1:
return maxLeft
else:
if i==m:
minRight = B[j]
elif j==n:
minRight = A[i]
else:
minRight = min(B[j],A[i])
return (maxLeft+minRight)/2
solution 2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
4. Median of Two Sorted Arrays
Hard
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
"""
class Solution:
def findMedianSortedArrays(self, x, y):
z = len(x) + len(y)
return self.findKth(x, y, z//2) if z % 2 == 1 \
else (self.findKth(x, y, z//2-1)+self.findKth(x, y, z//2))/2.0
def findKth(self, list1, list2, k):
if len(list1) > len(list2):
list1, list2 = list2, list1
if not list1:
return list2[k]
if k == len(list1) + len(list2) - 1:
return max(list1[-1], list2[-1])
i = len(list1) // 2
j = k - i
if list1[i] > list2[j]:
# Here it's O(1) to get list1[:i] and list2[j:].
return self.findKth(list1[:i], list2[j:], i)
else:
return self.findKth(list1[i:], list2[:j], j)
if __name__ == '__main__':
nums1 = (1, 2, 3, 4)
nums2 = (3, 4)
result = Solution().findMedianSortedArrays(nums1, nums2)
print(result)