[leedcode 04]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)).
public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { //此题利用二分法思想。题眼:看题目要求时间复杂度为O(log(m+n)) //通过每个数组的中位数将数组分成四个部分。通过判断k值和两个数组数组的中位数,按场景,不断舍弃每部分。此题需要注意下标的处理!!一定 要心细 int n1=nums1.length; int n2=nums2.length; if((n1+n2)%2==0){ return (find(nums1,0,n1,nums2,0,n2,(n1+n2)/2)+find(nums1,0,n1,nums2,0,n2,(n1+n2)/2-1))/2.0; }else{ return find(nums1,0,n1,nums2,0,n2,(n1+n2)/2); } } public double find(int[] nums1,int start1,int end1,int[] nums2,int start2,int end2,int k){ if(start1>=end1){ return nums2[k+start2]; }else if(start2>=end2){ return nums1[k+start1]; } int mid1=(start1+end1)/2; int mid2=(start2+end2)/2; if(k<=0){ return Math.min(nums1[start1],nums2[start2]); } if(k>mid1-start1+mid2-start2){ if(nums1[mid1]>=nums2[mid2]){ return find(nums1,start1,end1,nums2,mid2+1,end2,k-(mid2-start2)-1); }else{ return find(nums1,mid1+1,end1,nums2,start2,end2,k-(mid1-start1)-1); } }else{ if(nums1[mid1]>=nums2[mid2]){ return find(nums1,start1,mid1,nums2,start2,end2,k); }else{ return find(nums1,start1,end1,nums2,start2,mid2,k); } } } }