Description
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)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Code
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int n = (nums1Size >= nums2Size) ? nums1Size : nums2Size;
int m = nums1Size + nums2Size - n;
int *sn = (nums1Size >= nums2Size) ? nums1 : nums2;
int *sm = (nums1Size < nums2Size) ? nums1 : nums2;
int imin, imax, i, j, ihalf, max_left, min_right;
imin = 0; imax = m; ihalf = (m + n + 1)/2;
while(imin <= imax){
i=(imin + imax)/2;
j=ihalf-i;
if(i<m && sn[j-1]>sm[i])
imin = i+1;
else if(i > 0 && sm[i-1]>sn[j])
imax = i-1;
else{
if(i == 0)
max_left = sn[j-1];
else if(j == 0)
max_left = sm[i-1];
else
max_left = (sn[j-1] > sm[i-1]) ? sn[j-1] : sm[i-1];
if((m+n)%2 == 1)
return max_left;
if(i == m)
min_right = sn[j];
else if(j == n)
min_right = sm[i];
else
min_right = (sn[j] < sm[i]) ? sn[j] : sm[i];
return (min_right + max_left)/2.0;
}
}
return 0;
}
Reference
Discussion
- Understand the definition and find out the essential need of the problem.
- pseudo-code
- special cases analysis
- coding