LeetCode 1385. Find the Distance Value Between Two Arrays
考点 | 难度 |
---|---|
Sorting | Easy |
题目
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
.
思路
对arr2
排序,用binary search找到距离arr1[i]
最近的数。
答案
class Solution {
public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
Arrays.sort(arr2);
int res = 0;
for(int i=0;i<arr1.length;i++)
{
int close = findClosest(arr2,arr1[i]);
if(Math.abs(arr1[i]-close) > d)
res++;
}
return res;
}
int findClosest(int[] arr,int target)
{
int d = Integer.MAX_VALUE;
int low = 0,high = arr.length-1;
while(low <= high)
{
int mid = low + (high - low)/2;
if(arr[mid] == target)
return arr[mid];
else if(arr[mid] < target)
{
low = mid+1;
}
else
{
high = mid-1;
}
d = Math.abs(target-arr[mid]) < Math.abs(target-d) ? arr[mid] : d;
}
return d;
}
}