1385. Find the Distance Value Between Two Arrays

遍历 arr1,设 x=arr1[i]。我们要判断在 arr2 中是否存在元素,在闭区间 [x−d,x+d] 中。
排序arr2
考虑 [x−d,x+d] 中的第一个数(最左边的数),也就是在 arr2中二分查找 ≥x−d 的最小的数 y。如果 y 不存在,或者 y>x+d,则说明没有在 [x−d,x+d] 中的元素,符合题目要求,把答案加一。
js
var findTheDistanceValue = function (arr1, arr2, d) {
const binarySearch = (left, right, target) => {
const mid = Math.floor((left + right) / 2)
if (left === right) {
return mid
}
if (arr2[mid] < target) {
return binarySearch(mid + 1, right, target)
} else if (arr2[mid] > target) {
return binarySearch(left, mid, target)
} else {
return mid
}
}
arr2.sort((a, b) => a - b)
let ans = 0
for (const i of arr1) {
const min = i - d
const left = binarySearch(0, arr2.length, min)
if (left === arr2.length || arr2[left] > i + d) {
ans++
}
}
return ans
}