|
| 1 | +#!/usr/bin/python3 |
| 2 | +""" |
| 3 | +Winter is coming! Your first job during the contest is to design a standard |
| 4 | +heater with fixed warm radius to warm all the houses. |
| 5 | +
|
| 6 | +Now, you are given positions of houses and heaters on a horizontal line, find |
| 7 | +out minimum radius of heaters so that all houses could be covered by those |
| 8 | +heaters. |
| 9 | +
|
| 10 | +So, your input will be the positions of houses and heaters seperately, and your |
| 11 | +expected output will be the minimum radius standard of heaters. |
| 12 | +
|
| 13 | +Note: |
| 14 | +Numbers of houses and heaters you are given are non-negative and will not exceed 25000. |
| 15 | +Positions of houses and heaters you are given are non-negative and will not exceed 10^9. |
| 16 | +As long as a house is in the heaters' warm radius range, it can be warmed. |
| 17 | +All the heaters follow your radius standard and the warm radius will the same. |
| 18 | +""" |
| 19 | +import bisect |
| 20 | + |
| 21 | + |
| 22 | +class Solution: |
| 23 | + def findRadius(self, houses, heaters): |
| 24 | + """ |
| 25 | + check the responsibility |
| 26 | + use bisect |
| 27 | + :type houses: List[int] |
| 28 | + :type heaters: List[int] |
| 29 | + :rtype: int |
| 30 | + """ |
| 31 | + houses.sort() |
| 32 | + heaters.sort() |
| 33 | + r = 0 |
| 34 | + i = 0 |
| 35 | + for h in houses: |
| 36 | + i = bisect.bisect(heaters, h) # insertion point |
| 37 | + left = max(0, i - 1) |
| 38 | + right = min(len(heaters) - 1, i) |
| 39 | + r_cur = min(abs(heaters[left] - h), abs(heaters[right] - h)) |
| 40 | + r = max(r, r_cur) |
| 41 | + |
| 42 | + return r |
| 43 | + |
| 44 | + def findRadius_naive(self, houses, heaters): |
| 45 | + """ |
| 46 | + check the responsibility |
| 47 | + :type houses: List[int] |
| 48 | + :type heaters: List[int] |
| 49 | + :rtype: int |
| 50 | + """ |
| 51 | + houses.sort() |
| 52 | + heaters.sort() |
| 53 | + heaters.append(float('inf')) |
| 54 | + r = 0 |
| 55 | + i = 0 |
| 56 | + for h in houses: |
| 57 | + # possible bisect |
| 58 | + while h > (heaters[i] + heaters[i+1]) / 2: |
| 59 | + # find which heater is responsible for the house |
| 60 | + i += 1 |
| 61 | + |
| 62 | + r = max(r, abs(heaters[i] - h)) |
| 63 | + |
| 64 | + return r |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + assert Solution().findRadius([1,2,3,4], [1,4]) == 1 |
0 commit comments