?LeetCode刷題實(shí)戰(zhàn)475:供暖器
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.
示例? ? ? ? ? ? ? ? ? ? ? ? ?
示例 1:
輸入: houses = [1,2,3], heaters = [2]
輸出: 1
解釋: 僅在位置2上有一個供暖器。如果我們將加熱半徑設(shè)為1,那么所有房屋就都能得到供暖。
示例 2:
輸入: houses = [1,2,3,4], heaters = [1,4]
輸出: 1
解釋: 在位置1, 4上有兩個供暖器。我們需要將加熱半徑設(shè)為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);//這個地方當(dāng)時括號錯了,調(diào)了半天。
????????????if(heaters[mid]==house) return?0;
????????????if(heaters[mid]??????????????//如果當(dāng)前house>heater[mid],那我們向右縮小范圍
????????????????des=Math.min(des,Math.abs(house-heaters[mid]));
????????????????left=mid+1;
????????????}else{
????????????//當(dāng)前house
????????????????des=Math.min(des,Math.abs(house-heaters[mid]));
????????????????right=mid-1;
????????????}
????????}
????????return?des;
????}
}
LeetCode1-460題匯總,希望對你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)461:漢明距離
LeetCode刷題實(shí)戰(zhàn)462:最少移動次數(shù)使數(shù)組元素相等 II
LeetCode刷題實(shí)戰(zhàn)463:島嶼的周長
LeetCode刷題實(shí)戰(zhàn)464:我能贏嗎
LeetCode刷題實(shí)戰(zhàn)465:最優(yōu)賬單平衡
LeetCode刷題實(shí)戰(zhàn)466:統(tǒng)計(jì)重復(fù)個數(shù)
LeetCode刷題實(shí)戰(zhàn)467:環(huán)繞字符串中唯一的子字符串
LeetCode刷題實(shí)戰(zhàn)468:驗(yàn)證IP地址
LeetCode刷題實(shí)戰(zhàn)469:凸多邊形
LeetCode刷題實(shí)戰(zhàn)470:用 Rand7() 實(shí)現(xiàn) Rand10()
LeetCode刷題實(shí)戰(zhàn)471:編碼最短長度的字符串
LeetCode刷題實(shí)戰(zhàn)472:連接詞
LeetCode刷題實(shí)戰(zhàn)473:火柴拼正方形
LeetCode刷題實(shí)戰(zhàn)474:一和零
