There are two sorted arraysA 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)).
C++版本
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int * A = nums1;
int *B = nums2;
int m = nums1Size;
int n = nums2Size;
int preA = 0;
int endA = m-1;
int preB = 0;
int endB = n-1;
//if (endA <= 0 || endB <= 0) //不能随便直接返回,注意边界条件,否则第一个为[]第二个为[1]会失败!
// return 0;
double median;
//while (preA<endA && preB<endB){//关键的退出条件!
while ( (preA <= endA|| preB<=endB) && (getNum(preA, endA, A)+getNum(preB, endB, B)>2) ){
//cout<<"---"<<endl;
getMin(preA,endA,A)>getMin(preB,endB,B)?preB++:preA++;
getMax(preA,endA,A)>getMax(preB,endB,B)?endA--:endB--;
}
if (preA == endA && preB == endB){
return (A[preA] + B[endB])/2.0;
}
else if (preA == endA){
//return A[preA]/2.0; median理解错误!!
return A[preA];
}
else if (preB == endB){
//return B[preB]/2.0;
return B[preB];
}
else if (preA+1 == endA){ //此时不可能在B中只能有0个元素,及left>right
return (A[preA] + A[endA])/2.0;
}
else if (preB+1 == endB){ //此时不可能在B中只能有0个元素,及left>right
return (B[preB] + B[endB])/2.0;
}
}
int getMin(int left, int right, int num[]){
if (left>right) return INT_MAX; ///为什么不能返回0!!!!原因:::可能原数组中包含0元素!!!!!!
else return num[left];
}
int getMax(int left, int right, int num[]){
if (left>right) return INT_MIN;
else return num[right];
}
int getNum(int left, int right, int num[]){
if (left>right) return 0;
else
return right-left+1;
}
Java版
public class Solution {
public int getMin(int left, int right, int num[]){
if (left>right) return Integer.MAX_VALUE; ///为什么不能返回0,原因:可能原数组中包含0元素!
else return num[left];
}
public int getMax(int left, int right, int num[]){
if (left>right) return Integer.MIN_VALUE;
else return num[right];
}
public int getNum(int left, int right, int num[]){
if (left>right) return 0;
else
return right-left+1;
}
public double findMedianSortedArrays(int[] A, int[] B) {
int m = A.length;
int n = B.length;
int preA = 0;
int endA = m-1;
int preB = 0;
int endB = n-1;
double median;
while ( getNum(preA, endA, A)+getNum(preB, endB, B)>2 ){
//cout<<"---"<<endl;
if (getMin(preA,endA,A)>getMin(preB,endB,B))
preB++;
else
preA++;
if (getMax(preA,endA,A)>getMax(preB,endB,B))
endA--;
else
endB--;
}
if (preA == endA && preB == endB){
return (A[preA] + B[endB])/2.0;
}
else if (preA == endA){
//return A[preA]/2.0; median理解错误!!
return A[preA];
}
else if (preB == endB){
//return B[preB]/2.0;
return B[preB];
}
else if (preA+1 == endA){ //此时不可能在B中只能有0个元素,及left>right
return (A[preA] + A[endA])/2.0;
}
else if (preB+1 == endB){ //此时不可能在B中只能有0个元素,及left>right
return (B[preB] + B[endB])/2.0;
}
return 0;
}
}