[Leetcode]Median of Two Sorted Arrays
来源:互联网 发布:国内云计算市场份额 编辑:程序博客网 时间:2024/06/07 10:20
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)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
给出两个已经排序好的数组,算出两个数组的中位数
首先我的想法是先合并两个数组,然后根据个数,得到中位数的下表求出中位数
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ median = 0 nums = nums1 + nums2 m = len(nums) if(m%2==0): median=(nums[m/2]+nums[m/2+1])/2.0 else: median=nums[m//2+1] return(median)
虽然结果是对的,但是题目要求时间复杂度控制在O(log(m+n)),显然以上做法时间复杂度为O(m+n)。
然后网上看了别人用二分的思想
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] # @return a float 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
阅读全文
0 0
- 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
- 【转载】【leetcode】Median of Two Sorted Arrays
- LeetCode - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- 在CentOS中安装arm-linux-gcc-4.5.1-v6-vfp-20101103.tgz交叉编译环境
- 线段树
- Java多线程四种创建方式
- 2018阿里校招笔试——给定一个字符串S和有效单词的字典D,请确定可以插入到S中的最小空格数,使得最终的字符串完全由D中的有效单词组成,并输出解。
- device_create创建设备节点分析
- [Leetcode]Median of Two Sorted Arrays
- 并行编程与计算平台 | NVIDIA CUDA | NVIDIA --- GPU编程
- (十一)外观模式详解(Service第三者插足,让action与dao分手)
- 食物链(poj-1182)(带权并查集)
- python安装
- Monthly Expense POJ
- JVM结构、GC工作机制详解
- mysql联合索引
- OpenGL学习笔记之绘制图元