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

LeetCode 4.Median of Two Sorted Arrays

2016-09-05 19:27 399 查看
题目:

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)).
题意:
有2个大小分别为m,n的有序数组,找出2个数组中的中间数,整个复杂度应为O(log (m+n))

题解:

class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
num=nums1+nums2
num.sort()
length=len(num)
if length%2==0:
return (num[length/2]+num[length/2-1])/2.0
else:
return num[(length-1)/2]<span style="white-space:pre"> </span>直接sort(), 不过复杂度不满足

二分法,求有序数组中第K大数。

class Solution:
def findKthSortedArrays(self, A, B, k):
if len(A) < len(B):
tmp = A
A = B
B = tmp
if len(B) == 0:
return A[k - 1]
if k == 1:
return min(A[0], B[0])

pb = min(k / 2, len(B))
pa = k - pb
if A[pa - 1] > B[pb - 1]:
return self.findKthSortedArrays(A, B[pb:], k - pb)
elif A[pa - 1] < B[pb - 1]:
return self.findKthSortedArrays(A[pa:], B, k - pa)
else:
return A[pa - 1]

def findMedianSortedArrays(self, A, B):
if (len(A) + len(B)) % 2 == 1:
return self.findKthSortedArrays(A, B, (len(A) + len(B)) / 2 + 1)
else:
return (self.findKthSortedArrays(A, B, (len(A) + len(B)) / 2) +
self.findKthSortedArrays(A, B, (len(A) + len(B)) / 2 + 1)) / 2.0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python leetcode