您的位置:首页 > 编程语言

leetcode-4. Median of Two Sorted Arrays

2017-09-25 09:07 316 查看
https://leetcode.com/problems/median-of-two-sorted-arrays/description/

题意理解:二分找中位数,凑《=(m+n+1)/2的在a中的数,然后找到在b中的数

急转弯:先定a,再定b

算法:二分

数据结构:

#
#

'binary'

__author__ = 'hjkruclion'

import sys

def read_int():
return list(map(int, sys.stdin.readline().split()))

class Solution:
def b_b(self, m, x, b):
l = 0
r = m
while(l < r):
mid = (l + r) // 2
if b[mid] <= x:
l = mid + 1
else:
r = mid
return r - 1 + 1
def b_a(self, n, m, key, a, b):
l = 0
r = n
while(l < r):
mid = (l + r) // 2
res = mid + 1 + self.b_b(m, a[mid], b)
if res <= key:
l = mid + 1
else:
r = mid
return r - 1

def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
a = nums1
b = nums2
n = len(a)
m = len(b)
key = (n + m + 1) // 2
x = self.b_a(n, m, key, a, b)
# print(x)
num_x = x - 0 + 1
num_y = key - num_x
if x < 0:
L = b[num_y - 1]
else:
L = a[x]
if num_y - 1 >= 0:
L = max(a[x], b[num_y - 1])
if (n + m) % 2 == 1:
return L
else:
Ra = x + 1
Rb = num_y - 1 + 1
if Ra >= n:
R = b[Rb]
elif Rb >= m:
R = a[Ra]
else:
R = min(a[Ra], b[Rb])
return (L + R) / 2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 编程 leetcode