4. Median of Two Sorted Arrays (二分法;递归的结束条件)

时间:2021-09-11 19:25:55

There are two sorted arrays nums1 and nums2 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)).

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int len = nums1Size+nums2Size;
int median = len >> ;
if(len%==) {
if(nums1Size==) return nums2[median];
if(nums2Size==) return nums1[median];
return findK(nums1, , nums1Size, nums2, , nums2Size, median+);
}
else{
if(nums1Size==) return (double)(nums2[median-]+nums2[median])/;
if(nums2Size==) return (double)(nums1[median-]+nums1[median])/;
return (double)(findK(nums1, , nums1Size, nums2, , nums2Size, median)+findK(nums1, , nums1Size, nums2, , nums2Size, median+))/;
}
} int findK(int* nums1, int start1, int len1, int* nums2, int start2, int len2, int k){
if(len1==){ //check len = 1 case, because we keep median when recursion; otherwise, endless loop
if(nums1[start1] < nums2[start2+k-]) return nums2[start2+k-];
else{
if(k > len2 || nums1[start1] < nums2[start2+k-] ) return nums1[start1];
else return nums2[start2+k-];
}
}
if(len2==){
if(nums2[start2] < nums1[start1+k-]) return nums1[start1+k-];
else{
if(k > len1 || nums2[start2] < nums1[start1+k-] ) return nums2[start2];
else return nums1[start1+k-];
}
} int median1 = start1+(len1 >> ); //if len is odd, it's exactly median; else if even, it's the second of the two median
int median2 = start2+(len2 >> ); if(k <= ((len1+len2)>>)){ //k is at the first half
if(nums1[median1] < nums2[median2]){ //delete the second half of nums2
findK(nums1, start1, len1, nums2, start2, median2-start2, k); //1. delete from median (including median)
}
else{//delete the second half of nums1
findK(nums1, start1, median1-start1, nums2, start2, len2, k);
}
}
else{ //k is at the second half
if(nums1[median1] < nums2[median2]){ //delete the first half of nums1
findK(nums1, median1, len1-(median1-start1), nums2, start2, len2, k-(median1-start1)); //2. Each time delete half at most, so keep median
}
else{ //delete the first half of nums2
findK(nums1, start1, len1, nums2, median2, len2-(median2-start2), k-(median2-start2));
}
}
//From 1, 2, we can see, when only one element, it cannot be deleted, so the end loop condition is len = 1
}