leetcode-4 Median of Two Sorted Arrays
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)).
这道题刚开始的想法是归并后再求中位数,但是归并的时间复杂度是O(m+n)。
用二分法的思路,有一个重要结论,如果A[k/2-1]<B[k/2-1],那么A[0]~A[k/2-1]一定不是第k小的数。具体见http://blog.csdn.net/zxzxy1988/article/details/8587244
代码如下
double min(double a,double b) { return a<b?a:b; } double findKth(int* A,int m,int* B,int n,int k) { if(m>n) return findKth(B,n,A,m,k); //总是让m比n小 if(m == 0) return B[k-1]; if(k <= 1) return min(A[0],B[0]); int pa = min(k/2,m), pb = k-pa; if(A[pa-1] < B[pb-1]) { return findKth(A+pa,m-pa,B,n,k-pa); } else if(A[pa-1] > B[pb-1]) { return findKth(A,m,B+pb,n-pb,k-pb); } else return A[pa-1]; } double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { int len = nums1Size+nums2Size; if(len%2 == 1) //奇数 return findKth(nums1,nums1Size,nums2,nums2Size,len/2+1); else return (findKth(nums1,nums1Size,nums2,nums2Size,len/2)+ findKth(nums1,nums1Size,nums2,nums2Size,len/2+1))/2; }