题目
冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。在加热器的加热半径范围内的每个房屋都可以获得供暖。现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置,请你找出并返回可以覆盖所有房屋的最小加热半径。说明:所有供暖器都遵循你的半径标准,加热的半径也一样。
示例:
输入: houses = [1,2,3], heaters = [2]
输出: 1
解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。
方法一 :排序+双指针
这道题的思路就是先找出每间房子距离加热器的距离的最小值,然后再将这些最小值进行比较,找出这些最小值之中的最大值,这就是可以覆盖所有房屋的最小加热半径。
代码如下
class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);//先排序
Arrays.sort(heaters);
int radius = 0;
for(int i=0,j=0 ; i<houses.length ; i++){
int currentDistance = Math.abs(houses[i] - heaters[j]);//记录当前房子和加热器的距离
while(j<heaters.length-1
&& Math.abs(houses[i]-heaters[j]) >= Math.abs(houses[i]-heaters[j+1])){
j++;
currentDistance = Math.min(currentDistance,Math.abs(houses[i]-heaters[j]));//找到和第i个房子距离最小的加热器距离
}
radius = Math.max(currentDistance,radius);//找到距离最小值之中的最大值
}
return radius;
}
}