Find the median number of 2 arrays
Many methods
But the complexity of time is different.
1 Use the array copy method to dissolve two arrays first, then sort, find the median
ImportJava.lang.reflect.Array;Importjava.util.Arrays;Importjava.util.Collection;Importjava.util.Collections; Public class_004medianoftwosortedarrays { Public Static voidMain (string[] args) {inta[]={2,3,5,9}; intb[]={1,4,7,10,11}; System.out.println (Findmediansortedarrays (A, b)); } Public Static DoubleFindmediansortedarrays (intA[],intb[]) { int[] D3 =New int[A.length +B.length]; System.arraycopy (A,0, D3, 0, a.length); System.arraycopy (B,0, D3, A.length, B.length); Arrays.sort (D3); System.out.println (Arrays.tostring (D3)); returnd3.length%2!=0?d3[d3.length/2]/1.0: (D3[D3.LENGTH/2-1]+D3[D3.LENGTH/2])/2.0; } }
2 is loop-judged insert new array equals say don't use built-in copy method to write an alternative yourself
1 Importjava.util.Arrays;2 3 4 Public class_004_2median {5 6 Public Static voidMain (string[] args) {7 //TODO auto-generated Method Stub8 intA[]={2,34};9 intb[]={1,4,9};Ten System.out.println (Findmediansortedarrays (A, b)); One } A - Private Static DoubleFindmediansortedarrays (int[] A,int[] b) { - intk=a.length+b.length; the System.out.println (k); - int[] c=New int[K]; - intI=0,j=0,m=0; - while(m!=k) + { - if(i==a.length) + { Ac[m]=B[j]; atJ + +; - - } - Else if(j==b.length) - { -c[m]=A[i]; ini++; - } to Else if(a[i]<B[j]) + { -c[m]=A[i]; thei++; * $ }Panax Notoginseng Else - { thec[m]=B[j]; +J + +; A the + } -m++; $ } $ - returnK%2==0? (C[K/2-1]+C[K/2])/2.0:c[k/2]/1.0; - the } - Wuyi}
3 The third method of recursion needs to be studied
Median of Sorted Arrays (Java)