LeetCode : No4 Median of Two Sorted Arrays
来源:互联网 发布:三洋air9s性能数据 编辑:程序博客网 时间:2024/04/30 08:29
题目链接:
https://leetcode.com/problems/median-of-two-sorted-arrays/
该问题可以这样描述:在两个升序排列数组中,寻找第k小的数。中位数就是(m+n)/2小的数。则可以通过比较A[k/2-1]和B[k/2-1]的大小,剔除前k/2个较小的数字。在寻找第k-k/2小的数字,通过递归的方式,直至找到第(m+n)/2个值。
耗时:140ms
算法复杂度:O(log(m+n))
class Solution: # @return a float def findMedianSortedArrays(self, A, B): m = len(A) n = len(B) total = m + n if total%2 == 1: return float(self.findK(A,m,B,n,total/2+1)) else: return float(self.findK(A,m,B,n,total/2)+self.findK(A,m,B,n,total/2+1))/2 def findK(self, A, m, B, n, k): if (m>n): return self.findK(B,n,A,m,k) elif (m==0): return B[k-1] if k==1: return min(A[0],B[0]) pa = min(k/2,m) pb = k - pa if (A[pa-1] < B[pb-1]): return self.findK(A[pa:],m-pa,B,n,k-pa) elif (A[pa-1] > B[pb-1]): return self.findK(A,m,B[pb:],n-pb,k-pb) else: return A[pa-1]
0 0
- LeetCode : No4 Median of Two Sorted Arrays
- leetcode No4. Median of Two Sorted Arrays
- No4(Hard) Median of Two Sorted Arrays
- 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
- LeetCode-Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [leetcode] Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- 归并排序
- Android ActionBar使用方法
- go 语言 学习日记1(unknown)
- Android在处理图片减少出现OOM的方式
- 软件测试理论-基础2
- LeetCode : No4 Median of Two Sorted Arrays
- 【牛腩】——新闻发布系统收工
- android:为TextView添加样式——下划线,颜色,设置链接样式及前背景色
- 深度探索I/O完成端口
- 【基础html5 基础知识点】(全)
- apache.commons.compress zip压缩解压工具类完整版(使用递归支持无限文件夹的解压缩)
- 开源项目学习:Android-Universal-Image-Loader-Part1
- 网页刷新技术理论知识简单总结
- Mysql设计时该不该加约束