题目描述#

给你两个整数数组 arr1arr2 和一个整数 d ,请你返回两个数组之间的 距离值

距离值」 定义为符合此距离要求的元素数目:对于元素 arr1[i] ,不存在任何元素 arr2[j] 满足 |arr1[i]-arr2[j]| <= d

思路#

返回值规则#

Arrays.binarySearch() 是 Java 提供的二分查找方法,用于在一个已排序的数组中查找某个元素的位置。

它的原型为:

public static int binarySearch(int[] a, int key)

参数说明:

  • a:必须是升序排列的数组;
  • key:要查找的目标值;
  • 返回值:目标值在数组中的索引位置,如果找不到,会返回一个负数

Arrays.binarySearch 的返回值有两种情况:

情况 返回值 说明
找到了 x - d 索引 i 表示 arr2[i] == x - d
没找到 (-插入点 - 1) 其中 插入点(x - d) 应该插入的位置,使数组仍然有序

例如:

int[] arr2 = {1, 3, 5, 7, 9};
Arrays.binarySearch(arr2, 5);  // 返回 2
Arrays.binarySearch(arr2, 4);  // 返回 -3   插入点是 2

因为 4 应该插入在下标 2(即 3 和 5 之间),所以返回 -2 - 1 = -3

代码#

class Solution {
    public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
        Arrays.sort(arr2);
        int ans = 0;
        for (int i = 0; i < arr1.length; i++) {
            int index = Arrays.binarySearch(arr2, arr1[i] - d);
            if (index < 0) {
                index = -index - 1;
            }
            if (index == arr2.length || arr2[index] > arr1[i] + d) {
                ans++;
            }
        }
        return ans;
    }
}
你的IP 获取中…