今天和大家聊的问题叫做 供暖器,我们先来看题面:https://leetcode-cn.com/problems/heaters/
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater's warm radius range.
Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.
Notice that all the heaters follow your radius standard, and the warm radius will the same.
冬季已经来临。你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。在加热器的加热半径范围内的每个房屋都可以获得供暖。现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置,请你找出并返回可以覆盖所有房屋的最小加热半径。说明:所有供暖器都遵循你的半径标准,加热的半径也一样。
示例
示例 1: 输入: houses = [1,2,3], heaters = [2] 输出: 1 解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。 示例 2: 输入: houses = [1,2,3,4], heaters = [1,4] 输出: 1 解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。 示例 3: 输入:houses = [1,5], heaters = [2] 输出:3
解题
用二分查找法:前提是有序,所以我们先排序。
class Solution { public int findRadius(int[] houses, int[] heaters) { Arrays.sort(heaters); int ans=-1; for(int house:houses){ ans=Math.max(ans,findMinDest(house,heaters)); } return ans; } private int findMinDest(int house,int[] heaters){ int len=heaters.length-1; if(house>=heaters[len]) return (house-heaters[len]); if(house<=heaters[0]) return (heaters[0]-house); int des=Integer.MAX_VALUE; int left=0; int right=heaters.length-1; while(left<=right){ int mid=left+((right-left)>>1);//这个地方当时括号错了,调了半天。 if(heaters[mid]==house) return 0; if(heaters[mid]<house){ //如果当前house>heater[mid],那我们向右缩小范围 des=Math.min(des,Math.abs(house-heaters[mid])); left=mid+1; }else{ //当前house<heater[mid],那我们向左缩小范围 des=Math.min(des,Math.abs(house-heaters[mid])); right=mid-1; } } return des; } }
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。