Median of Two Sorted Arrays
来源:互联网 发布:虚拟桌面软件 编辑:程序博客网 时间:2024/04/29 13: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)).
Solution: 求两个有序数组的中位数,采用分治法,每次缩小搜索空间,分治法的基准点选择两个数组中位数。 该问题要注意m+n分别为奇偶的情况。
class Solution {public: int findk(vector<int>& a, vector<int>& b, int k){ int n = a.size(); int m = b.size(); if (n <= 0) return b[k-1]; if (m <= 0) return a[k-1]; if (k <= 1) return min(a[0], b[0]); if (b[m/2] >= a[n/2]) { if ((n/2 + 1 + m/2) >= k) { vector<int> b2(b.begin(), b.begin() + m/2); return findk(a, b2, k); } else{ vector<int> a2(a.begin() + n/2 + 1, a.end()); return findk(a2, b, k - (n/2 + 1)); } } else { if ((m/2 + 1 + n/2) >= k){ vector<int> a2(a.begin(), a.begin() + n/2); return findk( a2,b, k); } else{ vector<int> b2(b.begin() + m/2 + 1, b.end()); return findk( a,b2,k - (m/2 + 1)); } } } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(); int n = nums2.size(); if((m + n ) %2 == 0) { return (findk(nums1, nums2,(m + n)/2 ) + findk(nums1, nums2,(m + n)/2 + 1 )) / 2.0; } else return findk(nums1, nums2,(m + n)/2 + 1); }};
0 0
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of two sorted arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- median-of-two-sorted-arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- POJ——1001 求高精度幂
- 7月28日笔记
- Android 布局中的include标签使用
- JSON总结- JSON与JAVA的数据转换实例
- 处理键盘弹出
- Median of Two Sorted Arrays
- 微信企业号回调模式配置详细讲解
- pip2pi和pypiserver及Apache在pip本地源配置中的应用实践
- 如何使用RMI(Remote Method Invocation)
- OutOfMemoryError PermGen space
- 提高代码性能效率总结(二)--Java
- 仰视源码,实现memset
- 面试总结之Java基础(未完工)
- 如何删除Xcode中安装的插件