median-of-two-sorted-arrays
2016-12-10 18:08
162 查看
排序的代价过于高,我们可以采用挪动指针的方法找到第k大的值
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)).
参考了大神的代码:http://blog.csdn.net/zxzxy1988/article/details/8587244
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)).
参考了大神的代码:http://blog.csdn.net/zxzxy1988/article/details/8587244
#include <iostream> #include <map> #include <string> using namespace std; class Solution { public: double findMedianSortedArrays(int A[], int m,int B[], int n) { int k = (m+n)%2; if (k==0) return (f(A,m,B,n,(m+n)/2)+f(A,m,B,n,(m+n)/2+1))/2; else return f(A,m,B,n,(m+n)/2+1); } }; double f(int a[],int m,int b[],int n,int k) { if(m>n) return f(b,n,a,m,k); if(m==0) return b[k-1]; if(k==1) return min(a[0],b[0]); int pa = min(k/2,m),pb = k-pa; if(a[pa-1]<b[pb-1]) { return f(a+pa,m-pa,b,n,k-pa); } else if(b[pb-1]<a[pa-1]) { return f(a,m,b+pb,n-pb,k-pb); } else return b[pb-1]; }
相关文章推荐
- Leetcode[4]-Median of Two Sorted Arrays
- 【leetcode 数组】Median of Two Sorted Arrays
- LeetCode:Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- #4 Median of Two Sorted Arrays
- Median of Two Sorted Arrays(求两个数组的中位数)
- leetcode-4. Median of Two Sorted Arrays
- [LeetCode] 051: Median of Two Sorted Arrays
- LeetCode2:Median of Two Sorted Arrays
- ** Median of Two Sorted Arrays
- leet code 004:Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- MedianOfTwoSortedArrays
- Median of Two Sorted Arrays
- 算法分析与设计——LeetCode Problem.4 Median of Two Sorted Arrays
- leetcode : 4 Median of Two Sorted Arrays
- LeetCode:Median of Two Sorted Arrays