LeetCode-最小差

算法记录

LeetCode 题目:

  给定两个整数数组ab,计算具有最小差绝对值的一对数值(每个数组中取一个值),并返回该对数值的差。


说明

一、题目

输入: {1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}
输出: 3,即数值对(11, 8)
复制代码

二、分析

  • 要计算两个数组之间的最小值,那么在一般情况下肯定需要遍历所有的元素来比较,然后计算两两之间的最小值,这样的时间复杂度就是 O(n^2) 了。
  • 可以先将数组进行排序使用双指针来计算,这样就不用来回计算每个值之间的差值了,因为前面的元素和后面的元素的差值总是更大的。
  • 需要注意越界的问题。
class Solution {
    public int smallestDifference(int[] a, int[] b) {
        Arrays.sort(a);
        Arrays.sort(b);
        int min = 0, max = 0;
        long res = Long.MAX_VALUE;
        while(min < a.length && max < b.length) {
            long diff = a[min] - b[max];
            res = Math.min(Math.abs(diff), res);
            if(diff > 0) {
                max++;
            } else {
                min++;
            }
        }
        return (int) res;
    }
}
复制代码

总结

双指针使用。

猜你喜欢

转载自juejin.im/post/7106830591286312997