【Leetcode】【python】Median of Two Sorted Arrays
来源:互联网 发布:湖北楚天网络客服电话 编辑:程序博客网 时间:2024/06/08 20:09
题目大意
求两个已经排好序的数列的中位数
解题思路
转自:http://www.cnblogs.com/zuoyuan/p/3759682.html
首先我们来看如何找到两个数列的第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]小于B[2];则A[0],A[1],A[2]中必然不可能有第7个小的数。因为A[2]小于B[2],所以比A[2]小的数最多可能为A[0], A[1], B[0], B[1]这四个数,也就是说A[2]最多可能是第5个大的数,由于我们要求的是getKth(A, B, 7);现在就变成了求getKth(A’, B, 4);即A’ = {7};B不变,求这两个数列的第4个小的数,因为A[0],A[1],A[2]中没有解,所以我们直接删掉它们就可以了。这个可以使用递归来实现。
代码
class Solution(object): def getKth(self, A, B, k): lenA = len(A) lenB = len(B) if lenA > lenB: # 保证A比B短? return self.getKth(B, A, k) if lenA == 0: # A已为空,直接返回B中间数 return B[k - 1] if k == 1: return min(A[0], B[0]) pa = min(k/2, lenA) # print pa pb = k - pa # print pb # print A[pa - 1], B[pb - 1] 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): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ 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
总结
分治法,二分法
阅读全文
0 0
- Median of Two Sorted Arrays -- leetcode -- Python
- 【Leetcode】【python】Median of Two Sorted Arrays
- 【LeetCode with Python】 Median of Two Sorted Arrays
- [LeetCode]2 Median of Two Sorted Arrays (C++,Python实现)
- 4.Median of Two Sorted Arrays Leetcode Python
- leetcode 日经贴,python code -Median of Two Sorted Arrays
- [Leetcode]4. Median of Two Sorted Arrays @python
- 【LeetCode-Algorithm】【4-Median of Two Sorted Arrays】【Python】
- LeetCode 4.Median of Two Sorted Arrays (Python)
- 【leetcode】4. Median of Two Sorted Arrays(Python & C++)
- LeetCode: Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- leetcode Median of Two Sorted Arrays
- 大数据学习-hadoop入门
- Android Studio bmob 3.5.6 picasso2.5.2实物招领APP
- Ilya And The Tree(dfs,数学)
- [转]关于PreparedStatement.addBatch()方法
- linux工作中常用文件操作命令
- 【Leetcode】【python】Median of Two Sorted Arrays
- Redis在京东到家的订单中的使用
- POj 3420 (轮廓线dp)
- 数据结构与算法面试题
- java面试题(剑指offer):序列化二叉树
- Javaweb基础之response&request
- stm32 JTAG和SWD
- 优先队列-二叉堆Java实现
- 源码编译Python 64位版 GDAL2.2.1