2024/11/13 灵茶题单 二分查找
This commit is contained in:
parent
51b47be6aa
commit
1c6e61e745
|
@ -0,0 +1,42 @@
|
||||||
|
package com.cool.ling_cha_mount.binary_search;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author : Cool
|
||||||
|
* @date: 2024/11/13
|
||||||
|
* 1385. 两个数组间的距离值
|
||||||
|
*/
|
||||||
|
public class Num1385 {
|
||||||
|
public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
|
||||||
|
Arrays.sort(arr2);
|
||||||
|
int res = 0;
|
||||||
|
for (int num : arr1) {
|
||||||
|
int index = binarySearch(arr2, num);
|
||||||
|
if (index < arr2.length) {
|
||||||
|
int i = Math.abs(arr2[index] - num);
|
||||||
|
int j = Math.abs(arr2[index - 1 > -1 ? index - 1 : 0] - num);
|
||||||
|
if (i > d && j > d) {
|
||||||
|
res++;
|
||||||
|
}
|
||||||
|
} else if (Math.abs(arr2[index - 1] - num) > d) {
|
||||||
|
res++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int binarySearch(int[] nums, int target) {
|
||||||
|
int left = 0;
|
||||||
|
int right = nums.length - 1;
|
||||||
|
while (left <= right) {
|
||||||
|
int mid = (right - left) / 2 + left;
|
||||||
|
if (target <= nums[mid]) {
|
||||||
|
right = mid - 1;
|
||||||
|
} else {
|
||||||
|
left = mid + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue