題目地址:
https://www.lintcode.com/problem/the-smallest-difference/description
給定兩個數組和,求兩個數組中的各自兩個數使得其差的絕對值最小,返回這個最小的差的絕對值。
思路是先將兩個數組排序,然後用兩個指針分別從左向右遍歷數組,同時更新最終結果。如果則移動否則移動,類似貪心的想法,每次都使得接下來得到的差的絕對值更小。代碼如下:
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
Arrays.sort(A);
Arrays.sort(B);
int res = Integer.MAX_VALUE;
int i = 0, j = 0;
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;
}
}
時間複雜度。
算法正確性證明:
首先假定兩個數組排好序。算法的本質其實是枚舉。當的時候,和之後的所有數的差的絕對值只會更大,所以不需要枚舉;當的時候情況類似。而對於了所有的情況,上述算法要麼將其剪枝了,要麼就枚舉了它,所以算法是正確的。