==============================================================================
【id】#4
【title】Median of Two Sorted Arrays
【description】
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)).
You may assume nums1 and nums2 cannot be both empty.
【idea】
要求时间复杂度为O(log(m+n)),参考leetcode官网解析。
中位数概念:切割数组为两个等长的子集,且一边总是小于另一边。
对于数组A,B长度分别为 m,n
假设
left: A[0]…A[i-1]
right:A[i]…A[m]
左右等长,左边小于右边。
数组B同A
所以AB组合起来就是:
left_part | right_part
A[0], A[1], ..., A[i-1] | A[i], A[i+1],A[m-1]
B[0], B[1], ..., B[j-1] | B[j], B[j+1],B[n-1]
假设条件:
-
len(left_part)=len(right_part)
-
$ \max(\text{left\_part}) \leq \min(\text{right\_part})$
满足假设条件就要
- i+j=m−i+n−j (or: m - i + n - j + 1)
if n≥m, we just need to set: i = 0~m,
$ j = \frac{m + n + 1}{2} - i$
B[j-1]<=A[i] and A[i-1] <= B[j]
三种情况:
- if B[j-1] > A[i] : 说明A[i]小,imax后移imax=i+1
- if A[i-1] > B[j] : 说明A[i-1]大,imin前移imin=i-1
- if B[j-1] > A[i] : 说明A[i]小,imax后移imax=i+1,i正好
【code】
# 二分法
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
m, n = len(nums1),len(nums2)
if m > n :
nums1, nums2, m, n = nums2, nums1, n, m
if m ==0 :
return nums2[n//2] if n%2==1 else (nums2[n//2-1]+nums2[n//2])/2.0
imin, imax, half_len = 0, m, (m+n+1)/2
while imin <= imax:
i = int(imin + imax) /2
j = int(half_len - i)
if i < m and nums2[j-1] > nums1[i]:
# i too small
imin = i + 1
elif i >0 and nums1[i-1] > nums2[j]:
# i too big
imax = i - 1
else:
# i is perfect
if i == 0: max_left = nums2[j-1]
elif j == 0: max_left = nums1[i-1]
else : max_left = max(nums2[j-1], nums1[i-1])
if (m+n)%2 == 1: return max_left
if i == m: min_right = nums2[j]
elif j == n: min_right = nums1[i]
else: min_right = min(nums2[j], nums1[i])
return (min_right + max_left)/2.0
【拓展】
寻找第k小数k大数的 没想明白呢!!!?????
后续在更~~