题目描述
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)).
分析:
两种思路:
1. 直接 merge 两个数组,然后求中位数,能过,不过复杂度是 O(n + m)。
2. 用二分的思路去做,这不好想,还要考虑到奇偶。可以转化思维,去求两个有序数组中的第 K 大数,这样就比较好想了。
代码:
1. Merge
java:
package leetcode.easy.easy;
public class FindMedianSortedArrays {
/**
* @param args
*/
public static void main(String[] args) {
int[] A = new int[] {};
int[] B = new int[] { 2, 3 };
System.out.println(findMedianSortedArrays(A, B));
}
public static double findMedianSortedArrays(int A[], int B[]) {
int lenA = A.length;
int lenB = B.length;
int[] C = new int[lenA + lenB];
int i = 0, j = 0, k = 0;
if (lenA != 0 && lenB != 0) {
while (i < lenA || j < lenB) {
if (i == lenA) {
C[k++] = B[j++];
continue;
}
if (j == lenB) {
C[k++] = A[i++];
continue;
}
if (A[i] > B[j]) {
C[k++] = B[j++];
} else {
C[k++] = A[i++];
}
}
} else {
if (lenA == 0) {
while (j < lenB) {
C[k++] = B[j++];
}
}
if (lenB == 0) {
while (i < lenA) {
C[k++] = A[i++];
}
}
}
if ((lenA + lenB) % 2 == 1) {
return C[(lenA + lenB) / 2];
}
return (C[(lenA + lenB)/2 - 1] + C[(lenA + lenB)/2]) / 2.0;
}
}
C++:
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
vector<int> C;
int pa = 0, pb = 0; // point of A & B
while (pa < m || pb < n) {
if (pa == m) {
C.push_back(B[pb++]);
continue;
}
if (pb == n) {
C.push_back(A[pa++]);
continue;
}
if (A[pa] > B[pb])
C.push_back(B[pb++]);
else
C.push_back(A[pa++]);
}
if ((n + m)&1)
return C[(n+m)/2];
else
return (C[(n+m)/2 - 1] + C[(n+m)/2]) / 2.0;
}
};
2. 二分
java:
暂时没看懂,待补充