题目

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:

1
2
3
4
nums1 = [1, 3]
nums2 = [2]
The median is 2.0

Example 2:

1
2
3
4
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
m, n = len(nums1), len(nums2)
if m > n:
nums1, nums2 = nums2, nums1
m, n = n, m
imin, imax = 0, m
if n == 0:
raise ValueError
while imin <= imax:
i = (imin + imax) // 2
j = (m+n+1) // 2 - i
if i < m and nums2[j-1] > nums1[i]:
imin = i + 1
elif i > 0 and nums1[i-1] > nums2[j]:
imax = i - 1
else:
if i == 0:
lmax = nums2[j-1]
elif j == 0:
lmax = nums1[i-1]
else:
lmax = max(nums1[i-1], nums2[j-1])
if (m + n) % 2 == 1:
return lmax
if i == m:
rmin = nums2[j]
elif j == n:
rmin = nums1[i]
else:
rmin = min(nums1[i], nums2[j])
return (lmax + rmin) / 2