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.
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.
按照题目要求来看,就是在heaters上放置炉子,覆盖全部的houses,求距离最近炉子的最大半径。
思路:一个house可以选择两个炉子。左边的和右边的,哪个距离自己近,就选择被哪个炉子温暖,注意第一个heater左边的houses只能被第一个heater温暖,最后一个heater右边的
houses只能被最后一个heater温暖,其余中间的房子,均可以被左边和右边的同时温暖,在所有的最近的半径里面选择最大的半径,就是题目要求求出的半径。
java代码:
public class Solution { public int findRadius(int[] houses, int[] heaters) { Arrays.sort(houses); Arrays.sort(heaters); int max=0; for(int i=0;i<houses.length;i++) { //二分法找出第一个大于houses[i]的heater[mid] int left=0; int right=heaters.length-1; while(left<right)//for循环是用来求解距离自己最近的heater { int mid=left+(right-left)/2; if(houses[i]>heaters[mid]) { left=mid+1; } else right=mid; } if(right==0)//如果是第一个heater的话 距离就是用这个炉子减去房间的距离 max=Math.max(max,Math.abs(heaters[right]-houses[i])); else {//其余的话,都是和上一个炉子和这个炉子减去房间的距离,选择其中最小的 int distance1=Math.abs(heaters[right]-houses[i]); int distance2=Math.abs(houses[i]-heaters[right-1]); max=Math.max(max, Math.min(distance1, distance2));//在所有的距离里面选择最大值 } } return max; } }