Java for Leetcode 004 Median of Sorted Arrays

Source: Internet
Author: User

There is sorted arrays nums1 and nums2 of size M and N respectively. Find The median of the sorted arrays. The overall run time complexity should be O (log (m+n)).

Problem Solving Ideas:

Due to the requirement of time complexity O (log (m+n)) It is almost certainly the idea of recursion and division.

Since there was an algorithm for finding two decimal places in the array, the time complexity is O (log (m+n)), so the direct call can be

Reference Link: http://blog.csdn.net/yutianzuijin/article/details/11499917/

Java Reference Code:

 Public classSolution { Public Static DoubleFindkth (int[] nums1,intIndex1,int[] nums2,intIndex2,intk) {if(Nums1.length-index1 > Nums2.length-index2)returnfindkth (NUMS2, Index2, Nums1, index1, K); if(Nums1.length-index1 = = 0)            returnNums2[index2 + k-1]; if(k = = 1)            returnmath.min (Nums1[index1], nums2[index2]); intP1 = Math.min (K/2, nums1.length-index1), p2 = k-P1; if(Nums1[index1 + p1-1] < Nums2[index2 + p2-1])            returnFindkth (nums1, index1 + p1, Nums2, Index2, K-p1); Else if(Nums1[index1 + p1-1] > nums2[index2 + p2-1])            returnFindkth (Nums1, index1, NUMS2, Index2 + p2, K-p2); Else            returnNums1[index1 + p1-1]; }    Static  Public DoubleFindmediansortedarrays (int[] nums1,int[] nums2) {        if((nums1.length + nums2.length)% 2! = 0)            returnFindkth (nums1, 0, NUMS2, 0, (Nums1.length+ nums2.length)/2 + 1); Else            returnFindkth (nums1, 0, NUMS2, 0, (Nums1.length+ nums2.length)/2)                    /2 + findkth (nums1, 0, NUMS2, 0, (Nums1.length+ nums2.length)/2 + 1)/2; }}

Java for Leetcode 004 Median of 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.