Commit 01a25b1c by yangpengflag

Initial commit

parents
import bisect
class Solution(object):
def findRadius(self, houses, heaters):
"""
冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。
所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。
说明:
给出的房屋和供暖器的数目是非负数且不会超过 25000。
给出的房屋和供暖器的位置均是非负数且不会超过10^9。
只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。
所有供暖器都遵循你的半径标准,加热的半径也一样。
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
# 遍历房子,找到每个房子在加热器中的位置(排序好的加热器)算出距离该房子最近的左右两端加热器离房子的距离并取最小值。最后取出这些最小值中的最大值。边界加判断条件。
# 若没找到待查元素,返回该元素应该存在的第x位置的负值。
# Python: bisect.bisect_left:若找到待查元素,返回元素索引;
# 若没找到待查元素,返回该元素应该存在的位置的索引。
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
if __name__ == "__main__":
solution = Solution()
# houses,heaters = [1,2,3,4],[1,4]
# solution.findRadius(houses,heaters)
houses,heaters = [1,3,5,9],[1,4]
solution.findRadius(houses,heaters)
\ No newline at end of file
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