leetcode 004 Median of Two Sorted Arrays
先找第k个,再把第k个设为中间值就是答案。
类似二分查找的思想,k大于一半时小于一半时分别对应与不同的舍弃搜索范围的情况。
例如当k大于一半时,比较两个数组的中间元素,舍弃较小元素所属的数组的前一半,对剩余进行同样的查找(注意更新k,要减去该数组长度的一半)。这样每次缩小范围为原来的四分之三。
# 2018/03/09
# exercise on leetcode
class Solution():
def findMedianSortedArrays(self, A, B):
a, b = len(A), len(B)
if (a + b) & 1 == 0:
return (self.findKthOfTwoSortedArrays(A, B, int((a + b)/2)) +
self.findKthOfTwoSortedArrays(A, B, int((a + b)/2 - 1)))/2.0
else:
return self.findKthOfTwoSortedArrays(A, B, int((a + b)/2))
def findKthOfTwoSortedArrays(self, A, B, k):
if not A:
return B[k]
if not B:
return A[k]
if k == 0:
return min(A[0], B[0])
a, b = len(A), len(B)
if A[int(a/2)] >= B[int(b/2)]:
if k > int(a/2) + int(b/2):
return self.findKthOfTwoSortedArrays(A[:], B[int(b/2) + 1:], k - int(b/2) - 1)
else:
return self.findKthOfTwoSortedArrays(A[:int(a/2)], B[:], k)
else:
return self.findKthOfTwoSortedArrays(B, A, k)