[LeetCode] 1385. Find the Distance Value Between Two Arrays

Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.

The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.

Example 1:
Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
Explanation:
For arr1[0]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1[1]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=2

Example 2:
Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
Output: 2

Example 3:
Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
Output: 1

Constraints:
1 <= arr1.length, arr2.length <= 500
-1000 <= arr1[i], arr2[j] <= 1000
0 <= d <= 100

两个数组间的距离值。

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

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

思路

这道题的最优解是二分法。注意题设,对于元素 arr1[i],我们要去 arr2 里面看是否存在一个 arr2[j] 满足 |arr1[i]-arr2[j]| <= d 。暴力的做法就是线性扫描,但是这会使得整体的复杂度达到 O(n^2) 。

优化的思路是我们需要对 arr2 进行排序,这样我们可以用二分法来查找 arr2[j] 。但是排序过后,我们需要会拆解这个绝对值的式子。满足 |arr1[i] - arr2[j]| <= d,即是
-d <= arr1[i] - arr2[j] <= d
那么就是arr2[j] - d <= arr1[i] <= arr2[j] + d

也就是说arr1[i]需要介于 [arr2[j] - d, arr2[j] + d] 之间。此时我们就可以用二分法了。如果发觉元素 arr1[i] 不在这个区间内,则说明距离值不满足。

复杂度

时间O(nlogn)
空间O(1)

代码

Java实现

class Solution {
    public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
        Arrays.sort(arr2);
        int res = 0;
        for (int num : arr1) {
            int low = num - d;
            int high = num + d;
            if (!helper(low, high, arr2)) {
                res++;
            }
        }
        return res;
    }

    private boolean helper(int low, int high, int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= low && nums[mid] <= high) {
                return true;
            } else if (nums[mid] < low) {
                left = mid + 1;
            } else if (nums[mid] > high) {
                right = mid - 1;
            }
        }
        return false;
    }
}
posted @ 2024-11-14 09:31  CNoodle  阅读(3)  评论(0编辑  收藏  举报