Title Description:
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)).
Problem Solving Ideas:
This problem is difficult for people to solve the problem, you have to understand the points:
1. Find the median of a number with Len length, which can also be seen as the number of small len/2 (Len is odd), or the average number of LEN/2,LEN/2 +1 small number (len is even);
2. Also note that if you want to find two ordered array array1 and array2 in the nth small number, you can take a B to meet A+b=n, if array1[a-1]<array2[b-1], then array1[a] must be less than the nth small number. After these numbers can be excluded, continue to seek the remaining number of the N-a small number is the answer you want;
3. To reduce the value of a number to the desired value quickly, use the binary method to decrease the number of cycles.
The code is as follows:
1 Public classSolution {2 Public Static DoubleFindmediansortedarrays (int[] nums1,int[] nums2) {3 intlen1=nums1.length;4 intLen2=nums2.length;5 if(((LEN1+LEN2) &1) ==0){6 intCount= (LEN1+LEN2)/2;7 intNum1=fun (nums1,0,nums2,0, count);8 intNum2=fun (nums1,0,nums2,0,count+1);9 return(Double) (NUM1+NUM2)/2;Ten } One Else{ A intCount= (LEN1+LEN2)/2 +1; - intNum=fun (nums1,0,nums2,0, count); - the return(Double) num; - } - } - + Public Static intFunint[] nums1,intFrom1,int[] Nums2,intFrom2,intk) { - //Considering that the number in an array has all been excluded + if(from1>=nums1.length) { A returnNums2[from2+k-1]; at } - if(from2>=nums2.length) { - returnNums1[from1+k-1]; - } - //K=1 is the smallest, comparing the values from the from position in two arrays to - if(k==1){ in returnNUMS1[FROM1]<NUMS2[FROM2]?Nums1[from1]:nums2[from2]; - } to //To reduce the amount of code, ensure that the length of the nums1 is less than the length of Nums2 + if(nums1.length-from1>nums2.length-from2) { - int[] nums=nums1; the intFrom=from1; *nums1=Nums2; $from1=from2;Panax NotoginsengNums2=nums; -From2=from ; the } + //nums1 It is best to intercept the number of K/2 positions, but to ensure that no more than the number of the numbers that exist in the NUMS1 A intLen1 = Math.min (nums1.length-from1, K/2); the //guarantee Len1+len2=k; + intLen2 = k-len1; - if(nums1[from1+len1-1]>=nums2[from2+len2-1]){ $from2=from2+Len2; $ intresult = Fun (nums1,from1,nums2,from2,k-len2); - returnresult; - } the Else{ -from1=from1+len1;Wuyi intresult = Fun (nums1,from1,nums2,from2,k-len1); the returnresult; - } Wu - } About}
"Leetcode" 4. Median of Sorted Arrays