陆陆续续在LeetCode上刷了一些题,一直没有记录过,准备集中整理记录一下
class Solution {
public double findMedianSortedArrays(int[] A, int[] B) {
if ((A == null || A.length == 0) && (B == null || B.length == 0)) {
return -1.0;
}
int lenA = (A == null)?0:A.length;
int lenB = (B == null)?0:B.length;
int len = lenA + lenB;
int indexA = 0, indexB = 0, indexC = 0;
int[] C = new int[len];
//both A and B have elements
while (indexA < lenA && indexB < lenB) {
if (A[indexA] < B[indexB]) {
C[indexC++] = A[indexA++];
} else {
C[indexC++] = B[indexB++];
}
}
// only A has elements
while (indexA < lenA) {
C[indexC++] = A[indexA++];
}
//only B has elements
while (indexB < lenB) {
C[indexC++] = B[indexB++];
}
int indexM1 = (len - 1) / 2;
int indexM2 = len / 2;
if (len % 2 == 0) {
return (C[indexM1] + C[indexM2]) / 2.0;
} else {
return C[indexM2];
}
}
}
网友评论