标签:
Median of Two Sorted Arrays
问题:
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)).
思路:
二分查找变形
我的代码:
public class Solution { public double findMedianSortedArrays(int A[], int B[]) { int lenA = A.length; int lenB = B.length; if((lenA+lenB)%2 == 1) return (double)findKth(A,B,(lenA+lenB)/2+1); else return (findKth(A,B,(lenA+lenB)/2+1) + findKth(A,B,(lenA+lenB)/2))/(double)2; } public int findKth(int[] a, int[] b, int k) { int lenA = a.length; int lenB = b.length; if(lenA > lenB) return findKth(b, a, k); if(lenA == 0) return b[k-1]; if(k == 1) return Math.min(a[0],b[0]); int pa = Math.min(k/2,lenA); int pb = k - pa; if(a[pa-1] == b[pb-1]) return a[pa-1]; else if(a[pa-1] < b[pb-1]) return findKth(Arrays.copyOfRange(a, pa, lenA), b, k - pa); else return findKth(a, Arrays.copyOfRange(b, pb, lenB), k - pb); } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4390321.html