Leetcode 4: Given two ordered arrays, find the median value of two arrays.

Source: Internet
Author: User

My idea is that, since it is an ordered array, we can follow the idea of merging the sorting method, according to the final merging process.

Creates a new array, numbering the current positions of the two arrays and the merged array i,j,k.

Push the smaller values of the two arrays into the position of I, then the array of the extracted data and the merged array index +1.

The question to consider in this process is what to do if one of the arrays has been fully fetched.

Here's My Code:

classSolution { Public:    DoubleFindmediansortedarrays (vector<int>& Nums1, vector<int>&nums2) {size_t n= Nums1.size (), m=nums2.size (); Vector<int>Combine; intI=0, j=0, k=0;  for(; i<m+n;++i) {            if(j<n&&k<m) combine.push_back (Nums1[j]<nums2[k]?nums1[j++]:nums2[k++]); ElseCombine.push_back (J==n?nums2[k++]:nums1[j++]); }        if((m+n)%2==1)            returncombine[(m+n-1)/2]; Else            return(Combine[(m+n-1)/2]+combine[(m+n-1)/2+1])/2.0; }};

Leetcode 4: Given two ordered arrays, find the median value of two 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.