Median of two sorted arrays

Source: Internet
Author: User

given two ordered arrays of size m and n nums1 and nums2 . please find out the median of these two ordered arrays. The time complexity required for the algorithm is O (log (m+n)). you can assume that nums1 and nums2 are empty when they are different. Example 1:nums1 = [1, 3] nums2 = [2]
The median number is 2.0
Example 2:nums1 = [1, 2] nums2 = [3, 4]
Median is (2 + 3)/2 = 2.5
Self-thinking: 1. Find out the position of the median of two arrays after merging 2. From small to large, remove the number of corresponding positions from the two arrays difficulty: 1. Gets the position of the median. I am super confused with numbers, so how to get the median of the array needs to be noted. 2. By element size, iterate through the elements of the two ordered array and get the corresponding middle one or two numbers, thus obtaining the median. Idea: Starting with two array heads, comparing element sizes to a[m] and b[n] For example, the median position of these two arrays of M and N should be "(m+n-1)/2" or "(m+n-1)/2, (m+n-1)/2+1". (1) If a[0]>b[0], the first element of the merged array is b[0], and vice versa is a[0]. Note as Thisnum; (2) in 1 The larger number continues to compare with the next element of another array to get thisnum. (3) When the Thisnum is obtained "(m+n-1)/2" or "(m+n-1)/2, (m+n-1)/2+1", the median is recorded. 3. From the 2 idea, the framework of the algorithm can be implemented, but there will be some details: (1) How to record the median number of digits, is the record one or two (2) How to develop a small to large traversal array of rules algorithm implementation:
1 Importjava.io.IOException;2 Importjava.util.Arrays;3 ImportJava.util.Scanner;4 5  Public classMediansortedarrays {6      Public Static voidMain (string[] args)throwsioexception{7         /*Get input*/8Scanner input =NewScanner (system.in);9System.out.println ("Please enter the first array, separated by commas:"));Ten         int[] nums1=StringToArray (Input.nextline ()); OneSystem.out.println ("Please enter the second array, separated by commas:"); A         int[] nums2=StringToArray (Input.nextline ()); -System.out.println ("The median number of these two arrays is:"); -Solution getmedian=Newsolution (); the Arrays.sort (NUMS1); - Arrays.sort (NUMS2); -         Doublemedian=getmedian.findmediansortedarrays (NUMS1,NUMS2); - System.out.println (median); +     } -  +     /** A * Convert the acquired string to an array at      */ -      Public Static int[] StringToArray (String str) { -String[] strarr= str.split (","); -         int[] arr=New int[strarr.length]; -          for(inti=0;i<strarr.length;i++){ -arr[i]=Integer.parseint (Strarr[i].trim ()); in         } -         returnarr; to     } + } -  the  * classSolution { $      Public DoubleFindmediansortedarrays (int[] nums1,int[] nums2) {Panax Notoginseng         DoubleMidian; -         int[] Index=getindex (nums1.length+nums2.length); themidian=Getmedian (nums1,nums2,index); +         returnMidian; A     } the      +     /** - * Gets The median number of digits that should exist in the combined array $      * @paramArrlength $      * @return -      */ -      Public int[] GetIndex (intarrlength) { the         int[] index =New int[2]; -index[0]= (arrLength-1)/2;//(array length-1)/2 is one of the subscripts of the median in an ordered arrayWuyi         if(arrlength%2==0) {//when the array length is even, the median is (array length-1)/2 and (array length-1)/2+1 The average of the two subscript corresponding elements theIndex[1]=index[0]+1; -         } Wu         returnindex; -     } About      $     /** - * Get the median number -      * @paramnums1 -      * @paramNUMS2 A      * @paramIndex median subscript corresponds to array [(array length-1)/2, (array length-1)/2+1] or [(array length-1)/2,0] +      * @return the      */ -      Public DoubleGetmedian (int[] nums1,int[] Nums2,int[] index) { $         Doublesum=0;//The sum of two elements corresponding to the median of the record the         intMaxindex;//record the larger number of the median subscript array the         Doubleindexlength; the          the         /*This gets the median of the largest subscript as a loop marker*/ -         if(index[1]==0){ inMaxindex=index[0]; theIndexlength=1; the}Else{ AboutMaxindex=index[1]; theindexlength=2; the         } the          +         /*gets the sum of the corresponding subscript elements in a two array*/ -         intJ=0,k=0,thisindex=0,thisnum = 0; the          while(thisindex<=Maxindex) {Bayi             if(j<nums1.length&&k<nums2.length) {//When two arrays can be traversed the                 if(Nums1[j]>=nums2[k]) {//compares element size, when an array element is small, pushes the next element of the array theTHISNUM=NUMS2[K];//record the smaller elements of the comparison, as Thisnum -k++; -}Else{ thethisnum=Nums1[j]; theJ + +; the                 } the}Else{//When an array traversal is complete, but the median is still not found -                 if(j==nums1.length) {//The traversed array is no longer participating in the Thisnum record, only another array is traversed thethisnum=Nums2[k]; thek++; the                 }94                 if(k==nums2.length) { thethisnum=Nums1[j]; theJ + +; the                 }98             } About              -             if(Thisindex==maxindex) {//if the number of traversal reaches the middle-digit subscript requirement, do and, record the sum of the relative elements of the median number101sum+=Thisnum;102             }103             if(index[1]!=0&&thisindex==maxindex-1){104sum+=Thisnum; the             }106 107thisindex++;//Traverse Tag108         }109         returnSum/indexlength;//returns the median number the     }111}

After the Leetcode submission, the results run at 54ms, and the Leetcode fastest result is 32ms whose code is as follows
1 classSolution {2      Public DoubleFindmediansortedarrays (int[] nums1,int[] nums2) {3         intm = nums1.length, n = nums2.length, left = (m + n + 1)/2, right = (m + n + 2)/2;4         return(Findkth (NUMS1, NUMS2, left) + findkth (nums1, NUMS2, right)/2.0;5     }6     intFindkth (int[] nums1,int[] Nums2,intk) {7         intm = nums1.length, n =nums2.length;8         if(M > N)returnfindkth (Nums2, nums1, k);9         if(M = = 0)returnNums2[k-1];Ten         if(k = = 1)returnMath.min (Nums1[0], nums2[0]); One         inti = Math.min (M, k/2), j = math.min (n, K/2); A         if(Nums1[i-1] > Nums2[j-1]) { -             returnFindkth (Nums1, Arrays.copyofrange (Nums2, J, N), K-j); -}Else { the             returnFindkth (Arrays.copyofrange (nums1, I, M), NUMS2, K-i); -         } -     } -}

By comparison, it can be seen that 1. The depth and detail of the problem analysis is not enough, more inclined to brute force 2. The use of recursive algorithms is not recognized

Median number of two sorted arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.