标签:
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
题解:
最简单的思路是先归并两个数组,然后再找中位数,但是归并方法的时间复杂度是O(m+n)不是题目中要求的log(m+n).
log(m+n)的算法思路是:先把问题转换位找"第k小"问题,用反证法可以证明,如果nums1[k/2-1]<nums2[k/2-1] ,则nums1[0]到nums1[k/2-1]的元素都在nums1和nums2合并之后的前k小的元素中。换句话说,nums1[k/2-1]不可能大于两数组合并之后的第k小值,所以我们可以将其抛弃。
如果nums1[k/2-1]= nums2[k/2-1]则第k小恰好就是nums1[k/2-1] (或nums2[k/2-1]).
如果nums1[k/2-1] >nums2[k/2-1] 则有和 nums1[k/2-1] <nums2[k/2-1]类似的结果.
最后附上java版的代码:
public class Solution { protected double findKth(int[] a,int a_start,int[] b,int b_start,int k){ int m = a.length-a_start; int n = b.length-b_start; if(m>n) return findKth(b,b_start,a,a_start,k); if(m==0) return b[k-1]; if(k==1) return Math.min(a[a_start],b[b_start]); int pa = Math.min(k/2, m); int pb = k-pa; int indexa = a_start+pa-1; int indexb = b_start+pb-1; if(a[indexa]<b[indexb]){ return findKth(a,a_start+pa,b,b_start,k-pa); }else if(a[indexa]>b[indexb]){ return findKth(a,a_start,b,b_start+pb,k-pb); }else{ return a[indexa]; } } public double findMedianSortedArrays(int[] nums1, int[] nums2) { int total = nums1.length+nums2.length; if((total & 0x1)==1){ return findKth(nums1,0,nums2,0,total/2+1); }else{ return (findKth(nums1,0,nums2,0,total/2) +findKth(nums1,0,nums2,0,total/2+1))/2; } } }
Leet Code: 4. Median of Two Sorted Arrays
标签:
原文地址:http://www.cnblogs.com/feiqiangs/p/5769991.html