首页 > 其他 > 详细

The Smallest Difference

时间:2016-07-10 13:53:39      阅读:170      评论:0      收藏:0      [点我收藏+]

Given two array of integers(the first array is array A, the second array is arrayB), now we are going to find a element in array A which is A[i], and another element in array B which is B[j], so that 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], return 0。

分析:

首先sort, 然后用两个指针分别指向两个array的头部,谁小移动谁。

 1 public class Solution {
 2     /**
 3      * @param A, B: Two integer arrays.
 4      * @return: Their smallest difference.
 5      */
 6     public int smallestDifference(int[] A, int[] B) {
 7         Arrays.sort(A);
 8         Arrays.sort(B);
 9         
10         int pa = 0; 
11         int pb = 0;
12         
13         int diff = Integer.MAX_VALUE;
14         
15         while (pa < A.length && pb < B.length) {
16             if (A[pa] < B[pb]) {
17                 diff = Math.min(diff, Math.abs(A[pa] - B[pb]));
18                 pa++;
19             } else if (A[pa] == B[pb]) {
20                 return 0;
21             } else {
22                 diff = Math.min(diff, Math.abs(A[pa] - B[pb]));
23                 pb++;
24             }
25         }
26         return diff;
27     }
28 }

 

The Smallest Difference

原文:http://www.cnblogs.com/beiyeqingteng/p/5657480.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!