标签:遍历 pos 目的 最大值 sel turn ace 查找 为什么
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:
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.
此题虽然是easy题,但想法上不是很直接,细节上也有很值得注意的地方。
首先如果按照题目的想法,想着遍历heaters去包含houses,然后取最大值,这么想就偏了。正确的想法是遍历houses去计算离其最近的heaters,每一个house可以对应一个radius,然后再对这些radius取max就行了。这个转换的思想很关键。
在找到最近的heaters中有几个很重要的细节。
1. 什么时候将heaters的index前移。由于是遍历houses,heaters的index是不可能通过遍历来移动的,只能通过houses的index,在达到一定条件后前移。
这里的答案是当 下一个heater到当前house的距离 小于等于 当前heater到当前house的距离,即 abs(heaters[j+1] - houses[i]) <= abs(heaters[j] - houses[i] 。
2. 为什么用while不是if。
给出反例:
[1, 1, 100, 100]
[49, 50, 51]
当要连续跳过多个heater的情况。
3. 为什么判断距离时是 <= 不是 <
给出反例
[1,2,3,4,5,5,6,7,8,9]
[1,2,3,4,5,5,6,7,8,9]
当 abs(heaters[j+1] - houses[i]) 和 abs(heaters[j] - houses[i] 相等时,heater的index无法前移
class Solution: def findRadius(self, houses: List[int], heaters: List[int]) -> int: houses.sort() heaters.sort() j = 0 radius = 0 heaters_num = len(heaters) for i in range(len(houses)): while j < heaters_num - 1 and abs(heaters[j+1] - houses[i]) <= abs(heaters[j] - houses[i]): j += 1 radius = max(radius, abs(houses[i] - heaters[j])) print(j) return radius
二分查找
参考:
https://www.cnblogs.com/grandyang/p/6181626.html
标签:遍历 pos 目的 最大值 sel turn ace 查找 为什么
原文地址:https://www.cnblogs.com/sbj123456789/p/12178834.html