Young matrix K Small value/two array element and minimum value

Source: Internet
Author: User

Recently in the interview was asked an algorithm topic:
Given two ordered arrays a[] and b[], find the a[i]+b[j] of the K small.

Unfortunately, there is no answer on the spot ...

Back to check, in fact, this topic can also be converted to the young matrix in the K-small value. Do not know what is the young matrix, you can own Baidu. or simply as a matrix that is incremented for each column in each row.

This problem can be solved by the binary method, the specific algorithm is as follows:

 public int kthsum (int[] A, int[] b,int k) {int lena=a.length;
        int lenb=b.length;
        int max=a[lena-1]+b[lenb-1];
        int min=a[0]+b[0];
    return solve (A, B,max, Min, k);

        public int Solve (int[] a,int [] b,int max,int min, int k) {if (max==min) return Max;

        int mid= (MIN+MAX)/2;

        if (Counter (mid, A, b) >=k) return solve (A, B, Max, mid+1, K);

        if (Counter (mid-1, A, b) <k) return solve (A, B, Mid-1, Min, k);


    return mid;
        public int counter (int val,int[] a,int[] B) {int i=0;
        int j=b.length-1;
        int count=0;
                while (i<a.length&&j>=0) {if (a[i]+b[j]>val) {count = A.length-i;
            j--;
            }else {i++;
    } return count; }

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.