Median of Two Sorted Arrays
来源:互联网 发布:网络图编辑软件 编辑:程序博客网 时间:2024/05/01 12:20
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)).
哎,O(lgn)的算法写了半天写不下去了,在判断sub array长度的时候想不清楚。
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> res; int i = 0; int j = 0; while(i < m && j < n){ if(A[i] < B[j]){ res.push_back(A[i]); ++i; } else if(A[i] > B[j]){ res.push_back(B[j]); ++j; } else{ res.push_back(A[i]); res.push_back(B[j]); ++i; ++j; } } while(i < m){ res.push_back(A[i++]); } while(j < n){ res.push_back(B[j++]); } int total = m + n; if(total %2 == 0){ int mid = total /2; return (res[mid] + res[mid - 1]) / 2.0; } else{ int mid = total/2; return res[mid]; } }};
刚看到了一个lg(n)的解法,记下来。
class Solution {public:double findKth(int a[], int m, int 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[0], b[0]); int pa = min(k/2, m), pb = k - pa; if (a[pa-1] < b[pb-1]) return findKth(a+pa, m-pa, b, n, k - pa); else return findKth(a, m, b+pb, n-pb, k-pb); } double findMedianSortedArrays(int A[], int m, int B[], int n) { int total = m+n; if (total&0x1) return findKth(A, m, B, n, total/2+1); else return (findKth(A, m, B, n, total/2) + findKth(A, m, B, n, total/2+1))/2; }};
- 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
- Python常用辅助安全测试6个代码例子
- python 实现一个简单的 WebSocket 服务器
- Python调用C++动态链接库发送protobuf格式数据
- nyoj Light Bulb(三分方法,公式求解)
- 346. One never loses anything by politeness. 讲礼貌不吃亏
- Median of Two Sorted Arrays
- android 更改桌面图标
- Android TabHost 动态修改图标或者动态改变标题
- Linux文件编程(系统调用1)
- LeetCode: Merge Intervals
- Hadoop入门
- 下一代信息推荐系统的算法设计与性能评估
- shell语法
- Android仿QQ主界面-------完善篇