Python 中的加热器
pythonserver side programmingprogramming更新于 2026/1/27 18:52:17
假设我们必须设计一个具有固定加热半径的标准加热器来加热所有房屋。现在,我们给出了房屋和加热器在水平线上的位置,我们必须找到加热器的最小半径,以便所有房屋都能被这些加热器覆盖。因此,我们将分别提供房屋和加热器,我们预期的输出将是加热器的最小半径标准。
因此,如果输入为 [1,2,3,4],[1,4],则输出将为 1,因为两个加热器被放置在位置 1 和 4。我们必须使用半径 1,然后所有房屋都可以加热。
为了解决这个问题,我们将遵循以下步骤 −
对房屋列表进行排序
对加热器列表进行排序
res := 一个与房屋数组大小相同的数组,并使用 inf 填充它
对于范围从 0 到房屋大小的 i,执行
h := houses[i]
ind := 最左边的索引将 h 插入到加热器中,使列表保持排序
如果 ind 与加热器的大小相同,则
res[i] := res[i] 的最小值,|h - 加热器[-1]|
否则,当 ind 与 0 相同时,则
res[i] := res[i] 的最小值,|h - 加热器[0]|
否则,
res[i] := res[i] 的最小值,|h - 加热器[ind]| , |h - 加热器[ind-1]|
返回 res 的最大值
示例
让我们看下面的实现,以便更好地理解 −
from bisect import bisect_left
class Solution:
def findRadius(self, houses, heaters):
houses.sort()
heaters.sort()
res = [float('inf')]*len(houses)
for i in range(len(houses)):
h = houses[i]
ind = bisect_left(heaters, h)
if ind==len(heaters):
res[i] = min(res[i], abs(h - heaters[-1]))
elif ind == 0:
res[i] = min(res[i], abs(h - heaters[0]))
else:
res[i] = min(res[i], abs(h - heaters[ind]), abs(h - heaters[ind-1]))
return max(res)
ob = Solution()
print(ob.findRadius([1,2,3,4],[1,4]))
输入
[1,2,3,4],[1,4]
输出
1
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

