The Smallest Difference(最小差)

http://www.lintcode.com/zh-cn/problem/the-smallest-difference/?rand=true

import java.util.Arrays;

public class Solution {
    /*
     * @param A: An integer array
     * @param B: An integer array
     * @return: Their smallest difference.
     */
    public int smallestDifference(int[] A, int[] B) {
        // write your code here
//        先对数组进行排序,比较大小,小的就加1,两个越接近,差越小
        Arrays.sort(A);
        Arrays.sort(B);
        int i = 0;
        int j = 0;
        int res = Integer.MAX_VALUE;
        while (i < A.length && j < B.length) {
            res = Math.min(res, Math.abs(A[i] - B[j]));
            if (A[i] < B[j]) {
                i++;
            } else {
                j++;
            }
        }
        return res;
    }
}

你可能感兴趣的:(The Smallest Difference(最小差))