题目链接
法一
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int start = 0, max = 0;
for (int i = 0; i < houses.length; i++) {
int min = Integer.MAX_VALUE;
for (int j = 0; j < heaters.length; j++) {
if (Math.abs(houses[i] - heaters[j]) <= min) {
min = Math.abs(houses[i] - heaters[j]);
start = j;
} else {
break;
}
}
max = Math.max(max, min);
}
return max;
}
法二
public int findRadius_2(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int radius = 0, index = 0;
for (int house : houses) {
while (index < heaters.length && heaters[index] < house) {
index++;
}
if (index == 0) {
radius = Math.max(radius, heaters[index] - house);
} else if (index == heaters.length) {
return Math.max(radius, houses[houses.length - 1] - heaters[heaters.length - 1]);
} else {
radius = Math.max(radius, Math.min(heaters[index] - house, house - heaters[index - 1]));
}
}
return radius;
}
法三
private boolean check(int[] houses, int[] heaters, int r) {
int i = 0, j = 0;
while (i < houses.length && j < heaters.length) {
if (Math.abs(heaters[j] - houses[i]) <= r) {
i++;
} else {
j++;
}
}
if (i < houses.length) {
return false;
}
return true;
}
public int findRadius_3(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int left = 0, right = 1000000000;
while (left < right) {
int mid = left + (right - left) / 2;
if(check(houses, heaters, mid)){
right = mid;
}else {
left = mid + 1;
}
}
return left;
}
本地测试
lay.showTitle(475);
Solution475 sol475 = new Solution475();
int[] houses475 = new int[]{1,2,3,4};
int[] heaters475 = new int[]{1,4};
System.out.println(sol475.findRadius(houses475, heaters475));
System.out.println(sol475.findRadius_2(houses475, heaters475));
System.out.println(sol475.findRadius_3(houses475, heaters475));