475. Heaters
Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.
Note:
- Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
- Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
- As long as a house is in the heaters' warm radius range, it can be warmed.
- All the heaters follow your radius standard and the warm radius will the same.
Example 1:
Input: [1,2,3],[2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
Example 2:
Input: [1,2,3,4],[1,4] Output: 1 Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
Subscribe to see which companies asked this question
题目大意是给定一些房屋和一些加热器,输入房屋和加热器的一维坐标,输出加热器的最小加热范围使得所有房屋
都在加热器的加热范围中。
题目分析:
题目大概是一个max(min())的问题,就是计算出每一个房屋距离最近的加热器的距离,然后所有房屋这样的距离的最大值就是我们要的最小加热范围。
思路一:
一开始尝试用便利的做法结果超时了。后来先对加热器和房屋的数据进行排序,然后按照这样一个思路进行计算:
首先,一维坐标最小的房屋从第一个加热器开始计算距离。因为,加热器和房屋的坐标都是递增的,我们可以将这两个坐标看作一个递增函数。那么Math.abs(heaters(i)-houses(j)),是一个"V"型的函数。所以,Math.abs(heaters(i)-houses(j))递减,一旦下一个距离大于上一个距离说明取到了"V"的底部,可以跳出循环。
对于之后的房屋,其不必从第一个加热器开始计算,因为其相对前一个房屋坐标更大。其最优的加热器只可能再前一个房屋最优加热器之后,所以可以从前一个房屋计算出来的最近加热器开始计算。
代码:
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int resMin=100000000,resMax=0;
int startPoint=0;
for(int i=0;i<houses.length;i++){
resMin=2147483647;
for(int j=startPoint;j<heaters.length;j++){
if(Math.abs(houses[i]-heaters[j])<=resMin){
resMin = Math.abs(houses[i]-heaters[j]);
startPoint=j;
}else{
break;
}
}
if(resMin>resMax){
resMax = resMin;
}
}
return resMax;
}
运行结果: