leetcode04-Median of Two Sorted Arrays-python
来源:互联网 发布:数值的整数次方 java 编辑:程序博客网 时间:2024/06/03 12:30
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时间却更长。
0 0
- leetcode04-Median of Two Sorted Arrays-python
- leetcode04 Median of Two Sorted Arrays 两个已排序数组的中位数
- Median of Two Sorted Arrays -- leetcode -- Python
- 4. Median of Two Sorted Arrays-python
- 【Leetcode】【python】Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of two sorted arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- median-of-two-sorted-arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- iOS中的单例模式
- linux系统下mysql跳过密码验证登录
- Tomcat内存溢出的几点方案
- ${pageContext.request.contextPath} JSP路径问题
- Android中解决scrollview中嵌套listview的listview只显示一行的问题
- leetcode04-Median of Two Sorted Arrays-python
- 对RandomAccessFile类的应用
- 数据库索引
- 利用JSPatch为controller添加View
- Html5+CSS3+EL表达式问题集锦
- Glide之GlideModule
- OSI 七层模型
- js实现定时添加代码
- UNION 和UNION ALL 的区别