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

leetcode04-Median of Two Sorted Arrays-python

2016-03-31 15:11 555 查看
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)).

找两个序列的中位数。

想当然的思路将两个序列合二为一,找中位数。时间复杂度差。主要是有一个(m+n)大小的排序算法的复杂度。

经典排序算法的总结比较:这里写链接内容

复杂度平均情况为(m+n)log(m+n),与题目要求的log(m+n)不符,但是OJ通过。在网上找的更好的代码测试OJ时间反而更慢。

下面是自己写的。

class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
for i in nums2:
nums1.append(i)
nums1.sort()
k=len(nums1)
if k%2==0:
return (float(nums1[int(k/2-1)])+nums1[int(k/2)])/2
else:
return nums1[int((k-1)/2)]


摘抄部分:这道题其实考察的是二分查找,是《算法导论》的一道课后习题,难度还是比较大的。首先我们来看如何找到两个数列的第k小个数,即程序中getKth(A, B , k)函数的实现。用一个例子来说明这个问题:A = {1,3,5,7};B = {2,4,6,8,9,10};如果要求第7个小的数,A数列的元素个数为4,B数列的元素个数为6;k/2 = 7/2 = 3,而A中的第3个数A[2]=5;B中的第3个数B[2]=6;而A[2]

class Solution:
# @return a float
# @line20 must multiply 0.5 for return a float else it will return an int
def getKth(self, A, B, k):
lenA = len(A); lenB = len(B)
if lenA > lenB: return self.getKth(B, A, k)
if lenA == 0: return B[k - 1]
if k == 1: return min(A[0], B[0])
pa = min(k/2, lenA); pb = k - pa
if A[pa - 1] <= B[pb - 1]:
return self.getKth(A[pa:], B, pb)
else:
return self.getKth(A, B[pb:], pa)

def findMedianSortedArrays(self, A, B):
lenA = len(A); lenB = len(B)
if (lenA + lenB) % 2 == 1:
return self.getKth(A, B, (lenA + lenB)/2 + 1)
else:
return (self.getKth(A, B, (lenA + lenB)/2) + self.getKth(A, B, (lenA + lenB)/2 + 1)) * 0.5


二分法查找。使用起来没那么方便。效率高。最好的情况每次删除一半的元素,算法时间复杂度为log(m+n),上面的代码测试oj时间却更长。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: