描述
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater's warm radius range.
Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.
Notice that all the heaters follow your radius standard, and the warm radius will the same.
Example 1:
Input: houses = [1,2,3], heaters = [2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
Example 2:
Input: houses = [1,2,3,4], heaters = [1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
Example 3:
Input: houses = [1,5], heaters = [2]
Output: 3
Note:
1 <= houses.length, heaters.length <= 3 * 104
1 <= houses[i], heaters[i] <= 109
解析
根据题意,houses 和 heaters 排序之后,遍历 houses ,找出位置刚好在房子 i 之后的暖气 heaters[pos] ,然后判断房子 i 和 heaters[pos] 与 heaters[pos-1] 之间最小的距离,然后再将此距离与结果 r 比较最大值,遍历结束即可得到答案
解答
class Solution(object):
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
houses.sort()
heaters.sort()
ans = 0
pos = 0
heaters = [float('-inf')] + heaters + [float('inf')]
for house in houses:
while house >= heaters[pos]:
pos += 1
r = min(house - heaters[pos - 1], heaters[pos] - house)
ans = max(ans, r)
return ans
运行结果
Runtime: 212 ms, faster than 99.13% of Python online submissions for Heaters.
Memory Usage: 16 MB, less than 67.83% of Python online submissions for Heaters.
解析二
根据题意,遍历房子和暖气,将每个房子离自己最近的暖气的距离都放入列表中,然后找出最大值即是暖气最小的半径,此种解法太笨拙,超时,虽然可以在此基础上可以改进,但是耗时仍然很多。
解答
def findRadius( houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
d = []
for h in houses:
mi = float("inf")
for t in heaters:
mi = min(mi, abs(t-h))
d.append(mi)
return max(d)
原题链接:leetcode.com/problems/he…
您的支持是我最大的动力