Title: Median of sorted arrays
Knowledge Points: Two-point lookup, median definition
public class Solution {/* * about: Leetcode The second question given two sorted arrays, find their median, requirements: Time complexity O (log (m+n)); * Deformation: Find the number of K * method: 1. Traversal, time complexity is O (m+n), the number of two arrays is traversed from the beginning, by the size count, until the number of K * 2. Recursive, because two arrays are ordered, so the number of first K/2 is compared, the small side must all before the number of K (the absurdity) * Big side may not be all in the K, so recursion to find the remaining k/ 2 numbers. * Return Condition: 1. When an array is empty, return directly to the other array k number * 2.k=1, return min (a[0],b[0]) * 3.a[k/2-1] = = b[k/2-1], return one of the values */public double Findmediansort Edarrays (int a[], int b[]) {int n = a.length;int m = B.length;int total = n+m;if (total%2 = = 1) {//If the number of two arrays is added in odd numbers, you cannot have TOTAL&A mp;0x1 judgment. Return Culmedian (a,n,b,m,total/2+1);} Elsereturn (Culmedian (A,N,B,M,TOTAL/2) +culmedian (a,n,b,m,total/2+1))/2.0; }public double Culmedian (int a[],int n,int b[],int m,int k) {if (n = = 0) return b[k-1];if (m==0) return a[k-1];if (k = = 1) return A[0]<b[0]? A[0]:b[0];int A = K/2 < n? K/2: N; Note the consideration of boundary conditions int b = K-a < M? K-a: M;if (A[a-1] < b[b-1]) {//java cannot pass pointer directly with A+a ... Is there any other way??? int ia[] = new Int[n-a];for (int i = A;i < n;i++) Ia[i-a] = A[i]; Return Culmedian (IA,N-A,B,M,K-A);} else if (A[a-1] &Gt B[b-1]) {int ib[] = new Int[m-b];for (int i = B;i < m;i++) Ib[i-b] = B[i];return Culmedian (a,n,ib,m-b,k-b);} else return a[a-1]; }}
"Leetcode" median of the sorted arrays