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