(算法分析Week4)Median of Two Sorted Arrays[Hard]
来源:互联网 发布:医学英文写作软件 编辑:程序博客网 时间:2024/06/01 14:40
4. Median of Two Sorted Arrays
Description
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
Solution
忽略那些直接重新排序下标的做法。
找两个有序数组的中位数,拓展到找第K大的数。上算法分析课的时候已经说过思路:
取A[k / 2] 和B[k / 2] 比较,如果 A[k / 2] > B[k / 2] 那么,所求的元素必然不在B的前k / 2个元素中
反之,不在A的前k / 2个元素中,于是我们可以将A或B数列的前k / 2元素删去,求剩下两个数列的k - k / 2小元素,于是得到了数据规模变小的同类问题,递归解决。如果 k / 2 大于某数列个数,所求元素必然不在另一数列的前k / 2个元素中。
这道题要求中位数,只需要具体化k即可,注意奇偶数。
思路虽然清晰,但是写起代码还是遇到很多问题,比如奇数偶数的处理、剩下数组不足k/2等等,需要注意。
看到有一个博客总结的很好,在这里放个网址:http://blog.csdn.net/hk2291976/article/details/51107778
Complexity analysis
O(log(m+n)),两个长度为m和n的数组。
Code
#define min(x, y) x < y?x : y#define max(x, y) x < y?y : xclass Solution {public:double findkth(vector<int>::iterator a,int m, vector<int>::iterator 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 min(*a,*b); int c1 = min(k/2,m),c2 = k - c1; if(*(a + c1 - 1) < *(b + c2 -1)) return findkth(a+c1,m-c1,b,n,k-c1); else if(*(a + c1 -1) > *(b + c2 -1)) return findkth(a,m,b+c2,n-c2,k-c2); else return *(a+c1-1);}double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { auto n1 = nums1.begin(); auto n2 = nums2.begin(); int k = nums1.size() + nums2.size(); if(k % 2 == 1) return findkth(n1,nums1.size(),n2,nums2.size(),k/2+1); else return (findkth(n1,nums1.size(),n2,nums2.size(),k/2) + findkth(n1,nums1.size(),n2,nums2.size(),k/2 + 1))/2;}};
Result
阅读全文
0 0
- (算法分析Week4)Median of Two Sorted Arrays[Hard]
- 算法第三周Median of Two Sorted Arrays[hard]
- 算法设计与分析(3)-- Median of Two Sorted Arrays(难度:hard)
- Median of Two Sorted Arrays(hard)
- [Hard]Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays Hard
- 4. Median of Two Sorted Arrays Hard
- No4(Hard) Median of Two Sorted Arrays
- 算法分析课每周练习 Median of Two Sorted Arrays
- 算法分析与设计丨第三周丨LeetCode(5)——Median of Two Sorted Arrays(Hard)
- <LeetCode><Hard> 4 Median of Two Sorted Arrays
- [4, Hard, C++] Median of Two Sorted Arrays
- Hard-题目50:4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays(Hard)
- Leetcode 4. Median of Two Sorted Arrays (Hard) (cpp)
- LeetCode第四关:Median of Two Sorted Arrays --> Difficulty: Hard
- 4. Median of Two Sorted Arrays (Hard)
- LeetCode 4. Median of Two Sorted Arrays(Hard)
- mysql常用的sql语句收集
- 高级Lyapunov稳定性
- Java源码分析
- AD的“Un-Routerd Net Constraint:......”报错处理
- MongoDB 各种命令
- (算法分析Week4)Median of Two Sorted Arrays[Hard]
- 使用Mongo Connector和Elasticsearch实现模糊匹配
- Conquer a New Region HDU
- SpringMVC ajax技术无刷新文件上传下载删除示例
- sql(join on 和where的执行顺序)
- Db2性能问题:临时表空间太大,导致连不上数据库
- 数据科学家必须知道的10个深度学习架构
- intellij idea中如何运用码云托管项目
- 无法使用request.getContextPath()解决办法