面试刷题第11天
LeetCode刷题——475. 供暖器
1、题目描述
冬季已经来临。你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
在加热器的加热半径范围内的每个房屋都可以获得供暖。
现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置,请你找出并返回可以覆盖所有房屋的最小加热半径。
说明:所有供暖器都遵循你的半径标准,加热的半径也一样。
2、解题思路
(1)先给房屋和供暖器两个数组排序。
(2)供暖器数组,从小到大遍历,找到一个与第一个房屋的最小距离;依次遍历房屋,找到每个房屋所对应的供暖器的最小半径。
(3)返回所有半径中的最大值。
Java代码如下:
class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int ans = 0;
//i是地点,j是供暖点
for(int i=0, j=0; i<houses.length; i++){
while(!best(houses, heaters, i, j)){
j++;
}
ans = Math.max(ans, Math.abs(heaters[j] - houses[i]));
}
return ans;
}
public boolean best(int[] houses, int[] heaters, int i, int j){
return j==heaters.length-1 || Math.abs(heaters[j] - houses[i]) < Math.abs(heaters[j+1] - houses[i]);
}
}