1. 程式人生 > 其它 >具有給定數值的最小字串_面試題 16.06. 最小差

具有給定數值的最小字串_面試題 16.06. 最小差

技術標籤:具有給定數值的最小字串

給定兩個整數陣列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]內

解析:
注意該用例:[-2147483648,1]
            [2147483647,0]
如果用int型,會存在Math.abs(-2147483648-2147483647)溢位問題,見下圖,我們可以考慮轉換為abs(long);
如果用兩重迴圈,當陣列長度接近100000時,會發生超時,於是參考排序後雙指標;

class Solution {
    public int smallestDifference(int[] a, int[] b) {
        long res=Integer.MAX_VALUE;
        int aIndex=0,bIndex=0;
        Arrays.sort(a);
        Arrays.sort(b);
        while(aIndex<a.length&&bIndex<b.length){
            long x=a[aIndex];
            long y=b[bIndex];
            res=Math.min(res,Math.abs(x-y));
            if(x>y){
                bIndex++;
            }else{
                aIndex++;
            }
        }
        return (int)res;
    }
}
參考連結:https://leetcode-cn.com/problems/smallest-difference-lcci/solution/shuang-zhi-zhen-jie-jue-absyi-chu-fang-fa-by-lcbir/

c52ee4c671fda914c9b9ddd1b9dd31bb.png

5629f422f0fd7c373026e917c78c60d4.png