Find the Distance Value Between Two Arrays

给两个数组, 和一个数字d, 如果在一个数组中, 对应另一个数组的每两个元素对的差值小于d, 就算答案, 求在第一个数组中, 有几个这样的数字,

利用TreeSet找到第一个数组中每个个数字在另一个数组中最接近的ceiling和floor, 然后就可以知道这个差值是否小于d, 如果这个都大于d, 那么肯定不是答案. 这里注意ceiling和floor均有可能是null, 即当前数字是第二个数组中的最大或者最小值.

class Solution {
    public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
        TreeSet<Integer> set = new TreeSet<>();
        for(int n : arr2)
            set.add(n);
        int res = 0;
        for(int i = 0; i < arr1.length; i++) {
            Integer ceil = set.ceiling(arr1[i]);
            Integer floor = set.floor(arr1[i]);
            if(ceil == null) {
                if(Math.abs(arr1[i] - floor.intValue()) > d)
                     res++;
            }
            else if(floor == null) {
                if(Math.abs(arr1[i] - ceil.intValue()) > d)
                    res++;
            }
            else{
                if(Math.min(Math.abs(arr1[i] - ceil.intValue()), Math.abs(arr1[i] - floor.intValue())) > d)
                    res++;
            }
        }
        return res;
    }
}