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)).
https://leetcode.com/problems/median-of-two-sorted-arrays/
思路:利用二分查找
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
m = len(nums1); n = len(nums2)
if (m+n)%2 == 1:
return self.binarySearch(nums1, m, nums2, n, (m+n)/2+1)
else:
return float((self.binarySearch(nums1, m, nums2, n, (m + n) / 2) + self.binarySearch(nums1, m, nums2, n, (m + n) / 2 + 1))) / 2
def binarySearch(self, nums1, m, nums2, n, k):
if m<=0:
return nums2[k-1]
if n<=0:
return nums1[k-1]
if k<=1:
return min(nums1[0], nums2[0])
if nums1[m/2] > nums2[n/2]:
if (m/2 + n/2 +1 ) >= k:
return self.binarySearch(nums1, m/2, nums2, n, k)
else:
return self.binarySearch(nums1, m, nums2[n/2+1:n], n-n/2-1, k - n/2 -1)
else:
if(m/2 + n/2 +1 ) >= k:
return self.binarySearch(nums1, m, nums2, n/2, k)
else:
return self.binarySearch(nums1[m/2+1:m], m-m/2-1, nums2, n, k-m/2-1)

本文介绍了一种在两个已排序数组中找到中位数的方法,通过二分查找实现,确保了整体运行时间复杂度为O(log(m+n))。提供了一个Python实现示例。
598

被折叠的 条评论
为什么被折叠?



