Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater’s warm radius range.
Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that all houses could be covered by those heaters.
Input:
houses
and heaters
, where houses[i]
is the position of the i-th
house and heaters[j]
is the position of the j-th
heater.Output:
Example 1:
houses = [1,2,3]
, heaters = [2]
1
Example 2:
houses = [1,2,3,4]
, heaters = [1,4]
1
To solve this problem, we need to find the minimum radius required to cover all houses with the given heaters. The plan is:
houses
and heaters
arrays for easier calculation.Algorithm:
houses
and heaters
arrays.import bisect
def findRadius(houses, heaters):
houses.sort()
heaters.sort()
radius = 0
for house in houses:
# Use binary search to find the closest heater
pos = bisect.bisect_left(heaters, house)
# Calculate distances to the closest heaters
if pos == 0:
closest_heater_distance = abs(heaters[pos] - house)
elif pos == len(heaters):
closest_heater_distance = abs(heaters[-1] - house)
else:
closest_heater_distance = min(abs(heaters[pos] - house), abs(heaters[pos - 1] - house))
# Update the radius
radius = max(radius, closest_heater_distance)
return radius
# Example usage
houses = [1,2,3]
heaters = [2]
print(findRadius(houses, heaters)) # Output: 1
houses = [1,2,3,4]
heaters = [1,4]
print(findRadius(houses, heaters)) # Output: 1
houses
and heaters
takes (O(n \log n)) and (O(m \log m)), respectively, where (n) is the number of houses and (m) is the number of heaters.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?