LeetCode — Median of Two Sorted Arrays
来源:互联网 发布:人工智能 中英 百度云 编辑:程序博客网 时间:2024/06/05 08:30
Question:
There are two sorted arrays A and B 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)).
Solution:
这里的中位数定义取决于两数组合并大小的奇偶性,如果大小为奇数,中位数为中间值;如果是偶数,有两中间值,中位数则为两中间值求均值。
方案一:
先将两数组归并排好序,然后得出中位数,逻辑比较简单,时间复杂度为O(m+n).
方案二:
求中位数其实就是找第K小元素问题,同样用归并排序的原理,但维护一个计数,记录到找到第K个数位置停止,时间复杂度也到O(m+n).
方案三:
转化为求第K小元素问题,利用类似分治法的思想,每次剔除部分在第K小元素之前的元素,以达到优化算法的目的。此方案时间复杂度最优,为log(m+n), 实现如下:
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int Num = m + n; if (0 != Num%2) return findKthSmallest(A, m, B, n, Num/2 + 1); else return (findKthSmallest(A, m, B, n, Num/2) + findKthSmallest(A, m, B, n, Num/2 + 1) )/2; } double findKthSmallest(int A[], int m, int B[], int n, int K) { if (m > n) return findKthSmallest(B, n, A, m, K); if (0 == m) return B[K-1]; if (1 == K) return A[0] > B[0] ? B[0] : A[0]; int p = min(K/2, m); int q = K - p; if (A[p-1] == B[q-1]) return A[p-1]; else if(A[p-1] < B[q-1]) return findKthSmallest(A + p, m - p, B, n, K - p); else return findKthSmallest(A, m, B + q, n -q, K - q); }};
0 0
- 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 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
- 真因数
- java解析json,带转义字符的json
- MoveMessageDemo
- JVM -client和-server模式性能比较
- C++语言基础之标准输入cin
- LeetCode — Median of Two Sorted Arrays
- 怎样注册-反注册 ActiveX EXE
- 谷歌 25 招:如何构建优秀的移动网站
- DAVINCI DM6446 开发攻略——V4L2视频驱动和应用分析
- 九度 OJ 1049 字符串去特定字符
- delphi 中 delete的用法
- 回文数
- Spring实战 (五) 使用JPA
- 二分图最大匹配