Q:
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
A:
It can be converted to the problem of finding the kth number in the two sorted arrays.
- if (m+n)%2==1, k= (m+n)/2
- if (m+n)%2==0, k1= (m+n)/2 and k2 = (m+n)/2 -1, res = ([k1]+[k2])*0.5
Then, how to find the kth number?
We can compare the k/2-th numbers in array1 and arrary2.
- if array1[k/2] > array2[k/2], array1 = array1[ 0...k/2] array2 = array2[k/2+1,n]
- if array1[k/2] < array2[k/2], array1 = array1[k/2+1,n] array2 = array2[ 0...k/2]
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
if((m+n)%2==0){
return 0.5*( cal(nums1,nums2,(m+n)/2-1,0,m-1,0,n-1) + cal(nums1,nums2,(m+n)/2,0,m-1,0,n-1));
}else{
return cal(nums1,nums2,(m+n)/2,0,m-1,0,n-1);
}
}
int cal(int[] nums1, int[] nums2, int k, int s1, int e1, int s2, int e2){
if(s1>e1){
return nums2[s2+k];
}
if(s2>e2){
return nums1[s1+k];
}
if(k==0){
return nums1[s1]<nums2[s2]?nums1[s1]:nums2[s2];
}
int mid1 = k*(e1-s1+1)/(e1-s1+1+e2-s2+1); //important
int mid2 = k-mid1-1;
mid1 += s1;
mid2 += s2;
if(nums1[mid1]<nums2[mid2]){
k -= mid1-s1+1;
s1 = mid1+1;
e2 = mid2;
}else{
k -= mid2-s2+1;
s2 = mid2+1;
e1 = mid1;
}
return cal(nums1,nums2,k,s1,e1,s2,e2);
}
}