码迷,mamicode.com
首页 > 其他好文 > 详细

173.Heaters

时间:2018-09-17 21:32:00      阅读:205      评论:0      收藏:0      [点我收藏+]

标签: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:

  1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.您给出的房屋和加热器的数量是非负的,不会超过25000。
  2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.您给出的房屋和加热器的位置是非负的,不会超过10 ^ 9。
  3. As long as a house is in the heaters‘ warm radius range, it can be warmed.只要房屋处于加热器的温暖半径范围内,就可以加热。
  4. 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.
唯一的加热器放置在位置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即可满足要求。

173.Heaters

标签:ati   fir   差值   over   pos   math   numbers   解答   详解   

原文地址:https://www.cnblogs.com/chanaichao/p/9662869.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!