Leetcode 4:
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)).
简单的归并排序,将两个已排序的数组合成一个排序的数组。然后取中位数。
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
if (m + n == 0)return 0;
int *C = new int[m + n];
int j = 0, k = 0;
for (int i = 0; i < m + n; i++)
{
if (j < m&&k < n)
{
if (A[j] < B[k])
{
C[i] = A[j];
j++;
}
else
{
C[i] = B[k];
k++;
}
}
else if (j < m&&k == n)
{
C[i] = A[j];
j++;
}
else if (j == m && k < n)
{
C[i] = B[k];
k++;
}
}
if ((m + n) % 2)return C[(m + n) / 2];
else return (C[(m + n) / 2] + C[(m + n) / 2 - 1]) / 2.0;
}
};