"Leetcode" median of the sorted arrays

Source: Internet
Author: User

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

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.