Commit 44fbd452 by “安晓东”

供暖器

parent f0ab4d3e
# 供暖器
"""
冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。
所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。
说明:
给出的房屋和供暖器的数目是非负数且不会超过 25000。
给出的房屋和供暖器的位置均是非负数且不会超过10^9。
只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。
所有供暖器都遵循你的半径标准,加热的半径也一样。
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
# 遍历房子,找到每个房子在加热器中的位置(排序好的加热器)算出距离该房子最近的左右两端加热器离房子的距离并取最小值。最后取出这些最小值中的最大值。边界加判断条件。
# 若没找到待查元素,返回该元素应该存在的第x位置的负值。
# Python: bisect.bisect_left:若找到待查元素,返回元素索引;
# 若没找到待查元素,返回该元素应该存在的位置的索引。
# def findRadius(houses, heaters):
# heaters.sort()
# houses.sort()
# radius = 0
# i = 0
# # 哨兵
# heaters = [-1] + heaters + [float('inf')]
# for house in houses:
# while house > heaters[i]:
# i = i + 1
# current_radius = min(house - heaters[i - 1], heaters[i] - house)
# radius = max(radius, current_radius)
# print(radius)
# 方法一
def findRadius1(hourses, heaters):
heaters.sort() # 供暖器位置升序pailie
hourses.sort() # 房子的位置按升序排列
radius = 0
i = 0
heaters = [-1] + heaters + [float("inf")] # 给位置增加左右的最小值-1和最大值float(“inf”)为的房子在暖气位置的列表的第一位和最后一位时左右两边都有值
for hourse in hourses:
while hourse > heaters[i]: # 循环找到离房子最近的供暖器
i = i + 1
current_radius = min(hourse - heaters[i - 1], heaters[i] - hourse) # 求出每个房子离的最近的供暖器即最小值
radius = max(radius, current_radius) # 求出每个房子离最近供暖器最小值的最大值
houses, heaters = [1, 3, 5, 9], [1, 4]
findRadius1(houses, heaters)
import bisect
# 方法二
def findRadius(houses, heaters):
list.sort(heaters)
res = 0 # 半径
disleft = 0 # 每个房子离左边最近一个加热器的距离
disright = 0 # 每个房子离右边最近一个加热器的距离
for house in houses:
index = bisect.bisect_left(heaters, house) # 使用二分法获得房子在加热器中的位置,返回的是索引
print("房子%s在加热器中的位置:%s" % (house, index))
disleft = house - heaters[index - 1] if index - 1 >= 0 else float('inf') # 计算当前房子在取暖器中与前面最近一个取暖器的距离,当房子是第一个时,返回正无穷大
disright = heaters[index] - house if index < len(heaters) else float('inf') # 计算当前房子在取暖器中与后面最近一个取暖器的距离,当房子就是最后一个时取正无穷大
res = max(res, min(disleft, disright)) # 获取当前房子与左右2个取暖器位置距离的最小值,与其他房子在取暖器中的距离最小值比较,取最大的距离即可覆盖所有距离半径
print(res)
return res
houses, heaters = [1, 3, 5, 9], [1, 4]
findRadius(houses, heaters)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment