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
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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法