首页 > 代码库 > 475.Heaters java
475.Heaters java
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; } }
475.Heaters java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。