请教Find Median Of Two Sorted Arrays# JobHunting - 待字闺中
C*U
1 楼
我把leetcode上好多例子拿到机器上测试了 都没出错
但是在leetcode上会time limit exceeded
应该是有一个死循环
我找不出来
double findMedian(int A[], int m, int B[], int n) {
if(!n) {
return (A[(m - 1)/ 2] + A[(m - 1)/ 2 + (m - 1) % 2]) / 2.0;
}
int aStart = -1, aEnd = (m + n - 1) / 2 - 1;
int bStart = -1, bEnd = 0;
while(true) {
if(bEnd + 1 < n && A[aEnd] <= B[bEnd + 1] && B[bEnd] <= A[aEnd + 1])
{
break;
}
if(bEnd == n - 1 && B[bEnd] <= A[aEnd + 1]) {
break;
}
if(A[aEnd] < B[bEnd]) {
aStart = aEnd;
aEnd = aEnd + (bEnd - bStart + 1) / 2;
bEnd = bEnd - (bEnd - bStart + 1) / 2;
}
else if(A[aEnd] == B[bEnd]) {
break;
}
else {
bStart = bEnd;
if(bEnd + (aEnd - aStart + 1) / 2 < n) {
bEnd = bEnd + (aEnd - aStart + 1) / 2;
aEnd = aEnd - (aEnd - aStart + 1) / 2;
}
else {
aEnd = aEnd - (n - 1 - bEnd);
bEnd = n - 1;
}
}
}
if((m + n) % 2) {
return A[aEnd] > B[bEnd] ? A[aEnd] : B[bEnd];
}
else {
if(aEnd == -1) {
return (B[n - 1] + A[0]) / 2.0;
}
if(bEnd == -1) {
return aEnd == m - 1 ? (A[m - 1] + B[0]) / 2.0 : (A[aEnd] + A[
aEnd + 1]) / 2.0;
}
if(bEnd == n - 1){
return (A[aEnd] + (A[aEnd + 1] > B[bEnd] ? A[aEnd + 1] : B[bEnd]
)) / 2.0;
}
return ((A[aEnd] > B[bEnd] ? A[aEnd] : B[bEnd]) + (A[aEnd + 1] < B[
bEnd + 1] ? A[aEnd + 1] : B[bEnd + 1])) / 2.0;
}
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
if(m >= n) {
return findMedian(A, m, B, n);
}
else {
return findMedian(B, n, A, m);
}
}
但是在leetcode上会time limit exceeded
应该是有一个死循环
我找不出来
double findMedian(int A[], int m, int B[], int n) {
if(!n) {
return (A[(m - 1)/ 2] + A[(m - 1)/ 2 + (m - 1) % 2]) / 2.0;
}
int aStart = -1, aEnd = (m + n - 1) / 2 - 1;
int bStart = -1, bEnd = 0;
while(true) {
if(bEnd + 1 < n && A[aEnd] <= B[bEnd + 1] && B[bEnd] <= A[aEnd + 1])
{
break;
}
if(bEnd == n - 1 && B[bEnd] <= A[aEnd + 1]) {
break;
}
if(A[aEnd] < B[bEnd]) {
aStart = aEnd;
aEnd = aEnd + (bEnd - bStart + 1) / 2;
bEnd = bEnd - (bEnd - bStart + 1) / 2;
}
else if(A[aEnd] == B[bEnd]) {
break;
}
else {
bStart = bEnd;
if(bEnd + (aEnd - aStart + 1) / 2 < n) {
bEnd = bEnd + (aEnd - aStart + 1) / 2;
aEnd = aEnd - (aEnd - aStart + 1) / 2;
}
else {
aEnd = aEnd - (n - 1 - bEnd);
bEnd = n - 1;
}
}
}
if((m + n) % 2) {
return A[aEnd] > B[bEnd] ? A[aEnd] : B[bEnd];
}
else {
if(aEnd == -1) {
return (B[n - 1] + A[0]) / 2.0;
}
if(bEnd == -1) {
return aEnd == m - 1 ? (A[m - 1] + B[0]) / 2.0 : (A[aEnd] + A[
aEnd + 1]) / 2.0;
}
if(bEnd == n - 1){
return (A[aEnd] + (A[aEnd + 1] > B[bEnd] ? A[aEnd + 1] : B[bEnd]
)) / 2.0;
}
return ((A[aEnd] > B[bEnd] ? A[aEnd] : B[bEnd]) + (A[aEnd + 1] < B[
bEnd + 1] ? A[aEnd + 1] : B[bEnd + 1])) / 2.0;
}
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
if(m >= n) {
return findMedian(A, m, B, n);
}
else {
return findMedian(B, n, A, m);
}
}