Leetcode:Median of Two Sorted Arrays
来源:互联网 发布:剑三捏脸数据百度云 编辑:程序博客网 时间:2024/06/15 12:54
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
问题解析及算法描述
本题为两个有序数组合并后的中位数,若先不考虑时间复杂度的话,只需要从小到大依次数(m+n)/2个元素,从而转化成经典的找第k小的数的问题。
算法如下:同时遍历两个有序数组,比较数组的两个数的大小,若其中一个数组的数比较小则记录该数同时该数组的下标加一(即往后遍历新的数),否则记录另一数同时往后遍历另一个数组,直至遍历总数为(m+n)/2时;接下来,只需判断总数为奇数还是偶数,从而求得结果。
代码及其他算法实现
class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int size1 = nums1.size(), size2 = nums2.size(); int n = size1+ size2; int m = n/2; int v1 =0,v2 = 0; vector<int>::iterator it1 = nums1.begin(), it2 = nums2.begin(); for (int i = 0; i <= m; i++) { v1 = v2; if(it1 < nums1.end() && it2 < nums2.end()) { if (*it1 > *it2) { v2 = *it2; it2++; } else { v2 = *it1; it1++; } } else if (it1 < nums1.end()) { v2 = *it1; it1++; } else if (it2 < nums2.end()) { v2 = *it2; it2++; } } double median; if (n%2 == 0) median = (v1+v2)/2.0f; else median = v2; return median; }};
注意:该代码应用了归并计数算法复杂度为O((m+n)/2),并不符合题目要求的O(log(m+n))
因此,可采用分治算法解决两个有序数组中的中位数和Top K问题(该链接博主的思路比较清晰易懂)实现O(log(m+n))的复杂度,代码如下:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int n = nums1.size(); int m = nums2.size(); if(n > m) //保证数组1一定最短 return findMedianSortedArrays(nums2,nums1); int L1,L2,R1,R2,c1,c2,lo = 0, hi = 2*n; //我们目前是虚拟加了'#'所以数组1是2*n长度 while(lo <= hi) //二分 { c1 = (lo+hi)/2; //c1是二分的结果 c2 = m+n- c1; L1 = (c1 == 0)?INT_MIN:nums1[(c1-1)/2]; //map to original element R1 = (c1 == 2*n)?INT_MAX:nums1[c1/2]; L2 = (c2 == 0)?INT_MIN:nums2[(c2-1)/2]; R2 = (c2 == 2*m)?INT_MAX:nums2[c2/2]; if(L1 > R2) hi = c1-1; else if(L2 > R1) lo = c1+1; else break; } return (max(L1,L2)+ min(R1,R2))/2.0; }};
阅读全文
0 0
- 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
- 【转载】【leetcode】Median of Two Sorted Arrays
- LeetCode - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- Numpy-复制与视图
- ZOJ 2760 How Many Shortest Path 最短路+最大流
- CSDN 搜索自己博客文章
- Bootstrap学习
- 文摘:跑了1135 家制造企业,我终于明白它们是怎么把自己玩死的了
- Leetcode:Median of Two Sorted Arrays
- hdu2577(基础dp)
- JavaScript DOM操作
- Java程序---学生管理系统的登录和注册
- 初探AssetBundle
- dword ptr指令详细解析[转载]
- 2017秋招总结
- Python的iterable与iterator
- listview分页加载