您的位置:首页 > 其它

【LeetCode】475. Heaters 解题报告

2018-02-04 19:20 239 查看

【LeetCode】475. Heaters 解题报告

标签(空格分隔): LeetCode

题目地址:https://leetcode.com/problems/heaters/

题目描述:

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Note:

1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.

1. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.

1. As long as a house is in the heaters’ warm radius range, it can be warmed.

1. All the heaters follow your radius standard and the warm radius will the same.

Example 1:
Input: [1,2,3],[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: [1,2,3,4],[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.


解题方法

方法一:

这道题就是有一个加热器的地址列表,还有一个屋子列表,现在需要让你制定一个加热器的加热半径,使得所有的屋子都能被加热(加热器的位置就是加热器地址列表里的了)。

最朴素的思想。

题目给的不是有序的,一定要先排序,排序了之后,对houses进行遍历,找出大于house的最小的heater,然后求出house据左右的heater的最小距离。然后求出整个的最大距离,即为所求。

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


日期

2018 年 2 月 4 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: