The smallest difference

Source: Internet
Author: User

Given of integers (the first array is an array A , the second array is an array B ), now we were going to find a El Ement in array A which are a[i], and another element in array B which are b[j], so, the difference between a[i] and B[j] (| A[i]-b[j]|) is as small as possible, return their smallest difference.

Example

For example, given array A = [3,6,7,4] , B = [2,8,9,3] , return0。

Analysis:

First sort, and then with two pointers pointing to two arrays of the head, who moves the small one.

1  Public classSolution {2     /**3 * @param A, b:two integer arrays.4 * @return: their smallest difference.5      */6      Public intSmallestdifference (int[] A,int[] B) {7 Arrays.sort (A);8 Arrays.sort (B);9         Ten         intPA =0;  One         intPB =0; A          -         intdiff =Integer.max_value; -          the          while(PA < a.length && PB <b.length) { -             if(A[pa] <B[PB]) { -diff = math.min (diff, Math.Abs (a[pa)-B[PB])); -pa++; +}Else if(A[pa] = =B[PB]) { -                 return 0; +}Else { Adiff = math.min (diff, Math.Abs (a[pa)-B[PB])); atpb++; -             } -         } -         returndiff; -     } -}

The smallest difference

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.