Formatted question description: https://leetcode.ca/all/475.html

# 475. Heaters

Easy

## Description

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.

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.

## Solution

First sort the two arrays houses and heaters. Then for each house in houses, check whether it is at the same position as any heater in heaters. If so, the house is at one heater’s position so it can be warmed no matter what the warm radius is. Otherwise, consider the heaters adjacent to the house and the radius must be at least the distance from the house to its nearest heater.

Finding the house’s position in heaters is done by binary search.

• class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int heatersLength = heaters.length;
for (int house : houses) {
int index = binarySearch(heaters, house);
if (index >= 0)
continue;
index = -index - 1;
if (index == 0) {
int curRadius = heaters[index] - house;
} else if (index >= heatersLength) {
int curRadius = house - heaters[heatersLength - 1];
} else {
int heater1 = heaters[index - 1], heater2 = heaters[index];
int curRadius = Math.min(house - heater1, heater2 - house);
}
}
}

public int binarySearch(int[] array, int key) {
int low = 0, high = array.length - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
int num = array[mid];
if (num == key)
return mid;
else if (num > key)
high = mid - 1;
else
low = mid + 1;
}
return -low - 1;
}
}

• Todo

• class Solution(object):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
minDist = 0
heaters.sort()
for house in sorted(houses):
idx = bisect.bisect_left(heaters, house)
dist = float("inf")
if idx > 0:
dist = min(dist, abs(house - heaters[idx - 1]))
if idx < len(heaters) - 1:
dist = min(dist, abs(house - heaters[idx + 1]))
if idx < len(heaters):
dist = min(dist, abs(house - heaters[idx]))
minDist = max(minDist, dist)
return minDist