题目:

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

示例:

输入:{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}
输出: 3,即数值对(11, 8)
提示:

1 <= a.length, b.length <= 100000
-2147483648 <= a[i], b[i] <= 2147483647
正确结果在区间[-2147483648, 2147483647]内

分析:

现将两个数组排序,然后双指针从两个数组的头部向后扫描,哪个指针指向的元素小,该指针就向后移动。注意溢出的问题。

程序:

class Solution {
    public int smallestDifference(int[] a, int[] b) {
        Arrays.sort(a);
        Arrays.sort(b);
        int i = 0, j = 0;
        int res = Integer.MAX_VALUE;
        while(i < a.length && j < b.length){
            res = (int)Math.min(res, Math.abs((long)a[i] - (long)b[j]));
            if(a[i] < b[j])
                i++;
            else
                j++;
        }
        return res;
    }
}

 

相关文章:

  • 2021-09-21
  • 2021-07-06
  • 2021-11-06
  • 2022-01-29
  • 2021-11-14
  • 2021-10-18
  • 2021-05-22
  • 2022-01-20
猜你喜欢
  • 2021-09-03
  • 2021-05-25
  • 2021-06-05
  • 2022-03-08
  • 2021-08-17
  • 2021-12-12
  • 2021-12-31
相关资源
相似解决方案