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:

1
2
3
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:

1
2
3
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.

思路

我们如果利用暴力搜索的方法,会发现最终的结果是超时的。即便是用哈希表把访问过的差值储存起来也收效甚微。因为算法开销的大头已经是O(mn)了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def findRadius(self, houses, heaters):
length = len(houses)
visited = {}
for i in heaters:
for j in houses:
if (visited.has_key(j)):
if (abs(i-j) < visited[j]):
visited[j] = abs(i-j)
else:
visited[j] = abs(i-j)
p = visited.values()
radius = max(p)
return radius

首先把heater和houses都进行排序。在heater头尾加上边界,并将houses作为标杆来进行迭代。

我们找到元素左右两边的heater,从而找到离这个元素最近的heater,并算出半径。

维护一个最小的半径,即可得到最后的结果。我们可以将复杂度从O(mn) 降低到 O(m+n)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution(object):
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
lenhou = len(houses)
lenhea = len(heaters)
houses.sort()
heaters.sort()
heaters = [-(10 ** 12)] + heaters + [10 ** 12]
radius = 0
lpos = 0
rpos = 1
for i in houses:
while (rpos <= lenhea):
if (i > heaters[rpos-1] and i <= heaters[rpos]):
break
else:
rpos += 1
while (lpos < lenhea):
if (i < heaters[lpos+1] and i >= heaters[lpos]):
break
else:
lpos += 1
right = heaters[rpos]
left = heaters[lpos]
tmp = min(right - i, i - left)
if (tmp > radius):
radius = tmp
return radius

对于这个题目还有一种更加普适的解法,详见这篇讨论。

https://discuss.leetcode.com/topic/71813/more-challenging-problem-if-only-number-of-heaters-is-given-solution-and-details-comments-appreciated/3