LeetCode Median of Two Sorted Arrays
来源:互联网 发布:写漫画的软件 编辑:程序博客网 时间:2024/05/29 19:40
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(n+m)也可以通过,但是不符合题目的要求。
class Solution {public:double findMedianSortedArrays(int A[], int m, int B[], int n) {int *pArray = new int[m + n];int *ptemp = pArray;int i = 0, j = 0;while (i < m && j < n) {if (A[i] <= B[j])*ptemp++ = A[i++];else*ptemp++ = B[j++];}if (i < m)while (i < m)*ptemp++ = A[i++];elsewhile (j < n)*ptemp++ = B[j++];if ((m + n) % 2)return *(pArray + (m + n - 1) / 2);elsereturn 1.0 * (*(pArray + (m + n) / 2) + *(pArray + (m + n) / 2 - 1)) / 2;}};
虽然看到 log ,就想到要求出两个数组的中间值进行比较,然后想办法将区间缩小,但是仍然没有写出来。看了下网上其他人的解法。先附上链接:
http://blog.csdn.net/yutianzuijin/article/details/11499917
class Solution {public:double findMedianSortedArrays(int A[], int m, int B[], int n) {int length = m + n;if (length % 2)return findKth(A, m, B, n, length / 2 + 1);elsereturn (findKth(A, m, B, n, length / 2) + findKth(A, m, B, n, length / 2 + 1)) / 2;}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);int pb = k - pa;if (A[pa - 1] < B[pb - 1])return findKth(A + pa, m - pa, B, n, k - pa);else if (A[pa - 1] > B[pb - 1])return findKth(A, m, B + pb, n - pb, k - pb);elsereturn A[pa - 1];}};
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
- 人民币数字金额转大写金额
- HDU 1233 还是畅通工程
- HDU 4937 Lucky Number
- hdu 1007 Quoit Design 最近点对
- hdu-2068-Choose the best route
- LeetCode Median of Two Sorted Arrays
- 【Android开发-7】生命周期,Activity的生老病死
- Makefile多文件连接顺序问题
- poj 3468线段树延迟更新
- java中判断字符串是否为只包含数字
- 2014年8月12日晚 学习java的第一天
- Windows 下安装node-canvas
- POJ 2503 Babelfish(Trie)
- sublime text 3通过命令行安装package control插件