004 Median of Two Sorted Arrays [Leetcode]
来源:互联网 发布:营销软件广告 编辑:程序博客网 时间:2024/05/30 05:28
题目内容:
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)).
解题思路:
复杂度要求为O(log (m+n)),很容易让人想到二分查找。如果是一个长度为(m+n)的排序数组,那么直接使用二分查找就可以。但本题是在两个数组上进行的,那么在两个数组上进行二分查找会如何呢?
找中位数,若为奇数个,就是找第(m+n)/2个数;若为偶数个,就是找第(m+n)/2和第(m+n)/2+1个数的平均值。设我们要找的数是第k个。
1. 如果第一个数组的中间值与第二个数组的中间值相同,那么说明我们找到了中间值,即中间的这个数。
2. 如果第一个数组的中间值小于第二个数组的中间值,说明第一个数组中间值以前都不可能是前k个数,因此在剩余的数组中继续找前k-m/2个数
3. 如果第一个数组的中间值大于第二个数组的中间值,说明第二个数组中间值以前都不可能是前k个数,因此在剩余的数组中继续找前k-n/2个数
4. 注意处理数组变为空的情况
代码如下:
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int length(m+n); if(length%2) return findKth(A, m, B, n, length/2+1); else return (findKth(A, m, B, n, length/2)+findKth(A, m, B, n, length/2+1))/2.0; } int findKth(int A[], int m, int B[], int n, int K) { if(m>n) return findKth(B, n, A, m, K); if(m==0) return B[K-1]; if(K==1) return A[0]<B[0]?A[0]:B[0]; int pa(K/2<m?K/2:m); int pb(K-pa); if(A[pa-1]==B[pb-1]) return A[pa-1]; else if(A[pa-1]>B[pb-1]) return findKth(A, m, B+pb, n-pb, K-pb); else return findKth(A+pa, m-pa, B, pb, K-pa); }};
0 0
- leetcode-004:Median of Two Sorted Arrays
- [LeetCode]-004-Median of Two Sorted Arrays
- 004 Median of Two Sorted Arrays [Leetcode]
- [LeetCode]004-Median of Two Sorted Arrays
- Leetcode 004 Median of Two Sorted Arrays
- LeetCode 004 Median of Two Sorted Arrays *
- leetcode-004 Median of Two Sorted Arrays
- LeetCode 004 Median of Two Sorted Arrays
- LeetCode-004 Median of Two Sorted Arrays
- leetcode 004 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
- 深度学习算法原理——Softmax回归
- 欢迎使用CSDN-markdown编辑器
- 图的深度优先遍历(DFS)
- hibernate生成过后无报错500错误
- asterisk compiling with mp3
- 004 Median of Two Sorted Arrays [Leetcode]
- iOS消息推送注册
- Java 字符串比较 .equals, ==
- QuickSort -- 快速排序(C++)
- [转]AchartEngine属性
- 横竖屏切换时候Activity的生命周期
- 解决Mac OS X 10.11更新以后Cococapods找不到问题
- Hello!
- 虚函数和纯虚函数的区别