码迷,mamicode.com
首页 > 其他好文 > 详细

The Smallest Difference

时间:2016-07-10 13:54:22      阅读:136      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!