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
Python 1:
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
nums1=sorted(nums1+nums2)#组合并排序
return nums1[len(nums1)/2] if len(nums1)%2==1 else float(nums1[len(nums1)/2-1]+nums1[len(nums1)/2])/2#返回中值
Python 2:
import sys
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
if len(nums1)<len(nums2):
nums1,nums2=nums2,nums1
a,b=0,len(nums2)*2
while a<=b:
mid2=(a+b)/2
mid1=len(nums1)+len(nums2)-mid2
L1=nums1[(mid1-1)/2] if mid1!=0 else -sys.maxint-1
L2=nums2[(mid2-1)/2] if mid2!=0 else -sys.maxint-1
R1=nums1[(mid1)/2] if mid1!=len(nums1)*2 else sys.maxint
R2=nums2[(mid2)/2] if mid2!=len(nums2)*2 else sys.maxint
if L1>R2:
a=mid2+1
elif L2>R1:
b=mid2-1
else:
return float(max(L1,L2)+min(R1,R2))/2
题目要求时间复杂度不大于O(log (m+n)),因此第一种解决方案不能满足题目要求,但是代码和思想比较简单。第二种解决方案以二分查找为主要思想,通过找到两个list中的切分值,使其满足切分线左边的值小于右边的值,得到中值。
附上某不知名大神的详细解释(C++)