Median of Two Sorted Arrays
2015-07-05 00:09
375 查看
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)).
size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(); int n = nums2.size(); int value1 = KthValue(nums1, m, nums1.begin(), nums2, n, nums2.begin(), (m+n+1)/2); double result = value1; if (((m+n) & 1) == 0) { int value2 = KthValue(nums1, m, nums1.begin(), nums2, n, nums2.begin(), (m+n)/2+1); result = ((double)value1 + (double)value2)/2; } return result; } private: int KthValue(vector<int> &nums1, int size1, vector<int>::iterator it1, vector<int> &nums2, int size2, vector<int>::iterator it2, int k) { if (size1 > size2) { return KthValue(nums2, size2, it2, nums1, size1, it1, k); } if (size1 == 0) { return *(it2+k-1); } if (k == 1) { return min(*it1, *it2); } int offset1 = min(k/2, size1); int offset2 = k - offset1; if (*(it1+offset1-1) <= *(it2+offset2-1)) { return KthValue(nums1, size1-offset1, it1+offset1, nums2, offset2, it2, k-offset1); } else { return KthValue(nums1, offset1, it1, nums2, size2-offset2, it2+offset2, k-offset2); } } };
相关文章推荐
- spring security 3中关于ajax的处理
- Object的toString()方法
- 如何提升学习效率?
- 第九十三天 how can I 坚持
- SQL 注入 及SQLIer、SQLmap
- 判断物体是否在摄像机视野中
- Android中万能的适配器的详细讲解(附源代码)
- android开发之一如何升级SDK
- POJ 1056 解题报告 Trie 树
- 奇偶数分离
- #程序员健康 如何解救你的鼠标手
- 时间定位表达式-用于时间的加、减调整
- 用Fast Sweeping Method解Eikonal Equation方程
- Get the ID of a drawable in ImageView
- 【Android】ImageView的src和background的区别以及两者的妙用
- Lua学习
- A股上证指数日变化趋势聚类分析
- LeetCode Reverse Linked List (反置链表)
- php实现短信发送代码
- PHP中$_SERVER使用说明