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;
}
}