The Smallest Difference

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 }

 

posted @ 2016-07-10 12:45  北叶青藤  阅读(323)  评论(0编辑  收藏  举报