本题的考点是快排思想(第k最小数算法),要实现题目的复杂度要求难度还是不低的
时间复杂度:O(log(min(m, n)))
空间复杂度:O(1)
class Solution:
def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:
# Ensure nums1 is the shorter array to optimize the algorithm.
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
x, y = len(nums1), len(nums2)
start, end = 0, x
while start <= end:
partitionX = (start + end) // 2
partitionY = (x + y + 1) // 2 - partitionX
# If partitionX is 0 it means nothing is there on left side. Use -inf for maxLeftX
# If partitionX is length of input then there is nothing on right side. Use +inf for minRightX
maxLeftX = float('-inf') if partitionX == 0 else nums1[partitionX - 1]
minRightX = float('inf') if partitionX == x else nums1[partitionX]
maxLeftY = float('-inf') if partitionY == 0 else nums2[partitionY - 1]
minRightY = float('inf') if partitionY == y else nums2[partitionY]
if maxLeftX <= minRightY and maxLeftY <= minRightX:
if (x + y) % 2 == 0:
return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY)) / 2.0
else:
return max(maxLeftX, maxLeftY)
elif maxLeftX > minRightY: # Too far on right side for partitionX. Go on left side.
end = partitionX - 1
else: # Too far on left side for partitionX. Go on right side.
start = partitionX + 1
# Example usage
solution = Solution()
print(solution.findMedianSortedArrays([1, 2,3,5,6], [3, 4,5,8,9])) # Expected output: 2.5
float('-inf') 就是负无穷,符号表正负‘
nums1, nums2 = nums2, nums1,这一步确实没有产生新的空间,所以空间复杂度没问题,类似指针交换
其实这个代码我也不是理解的很透彻,不愧是困难题,学无止境了
题外话,不要过分关注leetcode上的用时和内存消耗,他的数据量可能比较小,用时看不出代码的好坏,还是要看时间复杂度和空间复杂度
推荐一款代码可视化工具Online Python Tutor - visualize, debug, get AI help for Python, Java, C, C++, and JavaScript