from bisect import bisect_right
class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
ans = 0
heaters.sort()
for house in houses:
# house存在于heaters中,则插在相同元素的右边
j = bisect_right(heaters, house)
i = j - 1
# 找到该house左右供暖器的最小加热半径,遍历每一个house
# 限自条件主要是下标越界问题,考虑好边界问题
# 第一种情况是j=len(heaters),第二种是i=-1的情况,都不要考虑进来,直接将他们的值设定成无穷大
distance_of_right = heaters[j] - house if j < len(heaters) else float('inf')
distance_of_left = house - heaters[i] if i >= 0 else float('inf')
distance_of_current = min(distance_of_left, distance_of_right)
ans = max(ans, distance_of_current)
return ans
LeetCode 475 供暖器
最新推荐文章于 2024-07-19 22:53:00 发布