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)).
http://leetcode.com/onlinejudge#question_4
复杂度没有达到要求的log(m+n) 而是O(m+n),就这还写了半天呢,妈蛋!
class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { double ans=0; int mid; if((m+n)%2!=0) { mid=(m+n)>>1; int i=0,j=0; while((i+j)<=mid) { if(i>=m||m==0) ans=B[j++]; else if(j>=n||n==0) ans=A[i++]; else { if(A[i]<=B[j]) ans=A[i++]; else ans=B[j++]; } } return ans; } else { mid=(m+n)>>1; int i=0,j=0; double tmp=0; while((i+j)<=mid) { tmp=ans; if(i>=m||m==0) ans=B[j++]; else if(j>=n||n==0) ans=A[i++]; else { if(A[i]<=B[j]) ans=A[i++]; else ans=B[j++]; } } return (tmp+ans)/2; } } };