题目
冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
在加热器的加热半径范围内的每个房屋都可以获得供暖。
现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置,请你找出并返回可以覆盖所有房屋的最小加热半径。
说明:所有供暖器都遵循你的半径标准,加热的半径也一样。
解题思路
二分查找。可以枚举供暖的半径,每次判断供暖器是否能覆盖所有房屋,直到不能完全覆盖。对于枚举的过程可以用二分加速。
代码
class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int left = 0, right = Math.max(houses[houses.length - 1], heaters[heaters.length - 1]);
while (left < right) {
int mid = (left + right) >> 1;
if (check(houses, heaters, mid)) right = mid;
else left = mid + 1;
}
return right;
}
private boolean check(int[] houses, int[] heaters, int mid) {
int lengthHouses = houses.length, lengthHeaters = heaters.length;
for (int i = 0, j = 0; i < lengthHouses; i++) {
while (j < lengthHeaters && houses[i] > heaters[j] + mid) j++;
if (j == lengthHeaters) return false;
if (!(houses[i] >= heaters[j] - mid && houses[i] <= heaters[j] + mid)) return false;
}
return true;
}
}