Skip to content

Commit 9597d1e

Browse files
Add files via upload
1 parent 269b4d6 commit 9597d1e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# 96 ms 93.73%
2+
# 借鉴答案的解题思路
3+
class Solution:
4+
def findMedianSortedArrays(self, nums1, nums2):
5+
"""
6+
:type nums1: List[int]
7+
:type nums2: List[int]
8+
:rtype: float
9+
"""
10+
m, n = len(nums1), len(nums2)
11+
12+
if n < m:
13+
return self.findMedianSortedArrays(nums2, nums1)
14+
15+
start, end = 0, m
16+
17+
while start <= end:
18+
19+
i = (start + end) // 2
20+
# 这里由于不管m+n是基数还是偶数,地板除把这两种情况统一为下面的一个公式了
21+
j = (m + n + 1) // 2 - i
22+
23+
a_left = nums1[i - 1] if i != 0 else float('-inf')
24+
a_right = nums1[i] if i != m else float('inf')
25+
26+
b_left = nums2[j - 1] if j != 0 else float('-inf')
27+
b_right = nums2[j] if j != n else float('inf')
28+
29+
if b_right >= a_left and a_right >= b_left:
30+
break
31+
elif a_right < b_left:
32+
start = i + 1
33+
else:
34+
end = i - 1
35+
36+
if (m + n) % 2 is 0:
37+
return (max(a_left, b_left) + min(a_right, b_right)) / 2
38+
else:
39+
# 如果是奇数的话,根据j的公式,中位数会出现在左边
40+
# 所以只需要从左边的两个边界值寻找就行了
41+
return max(a_left, b_left)

0 commit comments

Comments
 (0)