标签:ati fir 差值 over pos math numbers 解答 详解
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:
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.
唯一的加热器放置在位置2,如果我们使用半径1标准,那么所有的房屋都可以加热。
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.
两个加热器放置在位置1和4.我们需要使用半径1标准,然后所有房屋都可以加热。
方法一:
1 class Solution { 2 public int findRadius(int[] houses, int[] heaters) { 3 Arrays.sort(heaters); 4 int res=0,n=heaters.length; 5 6 for(int house:houses){ 7 int left=0,right=n; 8 while(left<right){ 9 int mid=left+(right-left)/2; 10 if(house>heaters[mid]) 11 left=mid+1; 12 else 13 right=mid; 14 } 15 16 int distance1=(right==n) ? Integer.MAX_VALUE:heaters[right]-house; 17 int distance2=(right==0) ? Integer.MAX_VALUE:house-heaters[right-1]; 18 res=Math.max(res,Math.min(distance1,distance2)); 19 } 20 21 return res; 22 } 23 }
先对heaters排序,然后用二分搜索法迅速找到heaters中第一个大于等于当前house位置的数,如果这个数存在,可以算出它和house的差值
如房屋house处于位置5,离它最近的heater为3和9,那么5-3=2,9-5=4,radis=2即可满足要求。
标签:ati fir 差值 over pos math numbers 解答 详解
原文地址:https://www.cnblogs.com/chanaichao/p/9662869.html