码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode #475 Heaters

时间:2020-01-11 09:22:40      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:遍历   pos   目的   最大值   sel   turn   ace   查找   为什么   

Question

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.
  2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
  3. As long as a house is in the heaters‘ warm radius range, it can be warmed.
  4. 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.

遍历

此题虽然是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

LeetCode #475 Heaters

标签:遍历   pos   目的   最大值   sel   turn   ace   查找   为什么   

原文地址:https://www.cnblogs.com/sbj123456789/p/12178834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!