题目地址:https://leetcode.cn/problems/heaters/description/
冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
在加热器的加热半径范围内的每个房屋都可以获得供暖。
现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置,请你找出并返回可以覆盖所有房屋的最小加热半径。
注意:所有供暖器 heaters 都遵循你的半径标准,加热的半径也一样。
// 思路:找到 houses[i] 距离 heaters[j] 的所有最小半径
// 在最小半径中取最大值
func findRadius(houses []int, heaters []int) int {
sort.Ints(houses)
sort.Ints(heaters)
radius := 0
cur := 0
j := 0
for i := 0; i < len(houses); i++ {
// 往后找到最小的半径
cur = absInt(houses[i] - heaters[j])
for j < len(heaters)-1 && absInt(houses[i]-heaters[j+1]) <= absInt(houses[i]-heaters[j]) {
j++
cur = absInt(houses[i] - heaters[j])
}
// 所有最小半径最大的那个
radius = max(radius, cur)
}
return radius
}
func absInt(num int) int {
if num < 0 {
return -num
}
return num
}
151

被折叠的 条评论
为什么被折叠?



