给你两个整数数组 arr1 , arr2 和一个整数 d ,请你返回两个数组之间的 距离值 。
距离值:定义为符合此距离要求的元素数目:对于元素 arr1[i] ,不存在任何元素 arr2[j] 满足 |arr1[i]-arr2[j]| <= d
第一种暴力破解:
public class Solution {
public static int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
int result = 0;
for (int j : arr1) {
boolean flag = true;
for (int k : arr2) {
if (Math.abs(j - k) <= d) {
flag = false;
break;
}
}
if (flag) {
result++;
}
}
return result;
}
public static void main(String[] args) {
int[] arr1 = {1,4,2,3};
int[] arr2 = {-4,-3,6,10,20,30};
int d = 3;
int theDistanceValue = findTheDistanceValue(arr1, arr2, d);
System.out.println(theDistanceValue);
}
}
// 增强for
public class Solution {
public static int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
int result = 0;
for (int j : arr1) {
boolean flag = true;
for (int k : arr2) {
if (Math.abs(j - k) <= d) {
flag = false;
break;
}
}
if (flag) {
result++;
}
}
return result;
}
public static void main(String[] args) {
int[] arr1 = {1,4,2,3};
int[] arr2 = {-4,-3,6,10,20,30};
int d = 3;
int theDistanceValue = findTheDistanceValue(arr1, arr2, d);
System.out.println(theDistanceValue);
}
}
第二种
package com.bg.day.D05;
import java.util.Arrays;
//二分查找改良
public class TwoPointsOfDistance {
private static final int ZERO = 0;
/**
*
* @param arr1 源数组
* @param arr2 比较数组
* @param d 距离值
* @return 满足距离值的个数
*/
public static int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
int result = ZERO;
for (int i : arr1) {
if (satisfyDistance(arr2, i, d)) {
result++;
}
}
return result;
}
/**
* 不满足距离值 返回false
* data 是源数组的值
*
* @return 是否满足距离值
*/
public static boolean satisfyDistance(int[] arr, int data, int distance) {
if (ZERO == arr.length) {
return false;
}
arr = Arrays.stream(arr).sorted().toArray();
int left = ZERO;
int right = arr.length - 1;
int mid;
while (left <= right) {
mid = (left + right) / 2;
if (Math.abs(arr[mid] - data) <= distance) {
return false;
} else if (arr[mid] > data) {
right = mid - 1;
} else if (arr[mid] < data) {
left = mid + 1;
}
}
return true;
}
public static void main(String[] args) {
int[] arr1 = {4,5,8};
int[] arr2 = {10,9,1,8};
int d = 2;
int theDistanceValue = findTheDistanceValue(arr1, arr2, d);
System.out.println(theDistanceValue);
}
}