For each element in arr1, we want to check if all elements in arr2 are at a distance greater than d. By sorting arr2, we can use binary search to efficiently check if there is any arr2[j] such that |arr1[i] - arr2[j]| <= d.
classSolution {
public:int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {
sort(arr2.begin(), arr2.end());
int ans =0;
for (int x : arr1) {
auto it = lower_bound(arr2.begin(), arr2.end(), x - d);
if (it == arr2.end() || abs(*it - x) > d) {
if (it == arr2.begin() || abs(*(it-1) - x) > d) ++ans;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
funcfindTheDistanceValue(arr1 []int, arr2 []int, dint) int {
sort.Ints(arr2)
ans:=0for_, x:=rangearr1 {
i:=sort.SearchInts(arr2, x-d)
ok:=trueifi < len(arr2) &&abs(arr2[i]-x) <=d {
ok = false }
ifi > 0&&abs(arr2[i-1]-x) <=d {
ok = false }
ifok {
ans++ }
}
returnans}
funcabs(aint) int { ifa < 0 { return-a }; returna }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintfindTheDistanceValue(int[] arr1, int[] arr2, int d) {
Arrays.sort(arr2);
int ans = 0;
for (int x : arr1) {
int i = Arrays.binarySearch(arr2, x - d);
if (i < 0) i =-i - 1;
boolean ok =true;
if (i < arr2.length&& Math.abs(arr2[i]- x) <= d) ok =false;
if (i > 0 && Math.abs(arr2[i-1]- x) <= d) ok =false;
if (ok) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funfindTheDistanceValue(arr1: IntArray, arr2: IntArray, d: Int): Int {
arr2.sort()
var ans = 0for (x in arr1) {
val i = arr2.binarySearch(x - d).let { if (it < 0) -it - 1elseit }
var ok = trueif (i < arr2.size && kotlin.math.abs(arr2[i] - x) <= d) ok = falseif (i > 0&& kotlin.math.abs(arr2[i-1] - x) <= d) ok = falseif (ok) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
deffindTheDistanceValue(self, arr1: list[int], arr2: list[int], d: int) -> int:
from bisect import bisect_left
arr2.sort()
ans =0for x in arr1:
i = bisect_left(arr2, x - d)
ok =Trueif i < len(arr2) and abs(arr2[i] - x) <= d:
ok =Falseif i >0and abs(arr2[i-1] - x) <= d:
ok =Falseif ok:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnfind_the_distance_value(arr1: Vec<i32>, mut arr2: Vec<i32>, d: i32) -> i32 {
arr2.sort();
letmut ans =0;
for&x in&arr1 {
let i = arr2.binary_search(&(x - d)).unwrap_or_else(|i| i);
letmut ok =true;
if i < arr2.len() && (arr2[i] - x).abs() <= d { ok =false; }
if i >0&& (arr2[i-1] - x).abs() <= d { ok =false; }
if ok { ans +=1; }
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
findTheDistanceValue(arr1: number[], arr2: number[], d: number):number {
arr2.sort((a, b) =>a-b);
letans=0;
for (constxofarr1) {
letl=0, r=arr2.length-1, ok=true;
while (l<=r) {
constm= (l+r) >>1;
if (arr2[m] <x-d) l=m+1;
elser=m-1;
}
if (l<arr2.length&& Math.abs(arr2[l] -x) <=d) ok=false;
if (l>0&& Math.abs(arr2[l-1] -x) <=d) ok=false;
if (ok) ans++;
}
returnans;
}
}