4. Median of Sorted Arrays
There is sorted arrays nums1 and nums2 of size M and N respectively.
Find The median of the 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
Example 2:
NUMS1 = [1, 2]NUMS2 = [3, 4]the median is (2 + 3)/2 = 2.5
The main problem: to find the median
Implementation method
Public classSolution { Public DoubleFindmediansortedarrays (int[] nums1,int[] nums2) { Doubleres=0.00; intn=nums2.length; //judging the non-empty situation if(nums1==NULL){ returnRes=nums2[n/2]; } intm=nums1.length; if(nums2==NULL){ returnRes=nums1[m/2]; } //Create a flag to mark whether this is an odd or an even number intcarry= (m+n)%2; //establish the flag bit, if it is odd, right is the middle value mid intleft= (m+n)/2-1; intright= (m+n)/2; //Open a m+n space actually only use half, if to save space can use int[] num =New int[m+N]; intI=m-1,j=n-1; intIndex=m+n-1; //sort two arrays (middle value-last sort) while(index>Left ) { while(i>=0&&j>=0) {Num[index--]= (Nums1[i]>nums2[j])? nums1[i--]:nums2[j--]; } while(i>=0) {Num[index--]=nums1[i--]; } while(j>=0) {Num[index--]=nums2[j--]; } }//End if(carry>0) //Middle value of odd positionres = (Double) Num[right]; Else{ //median value of even positionRes= (Double) (Num[left]+num[right])/2; } returnRes; }}
4. Median of the Sorted Arrays "Leetcode" Java, algorithm, intermediate value