The first thing that comes to mind is to find the distance r of all heaters that are the shortest distance from the house, and then return the largest r
var findRadius = function(houses, heaters) {
var max = 0 for(let i = 0 ; i < houses.length ; i ++) {
var house_position = houses[i]
var r = Infinity for(let j = 0 ; j < heaters.length ; j ++) {
var heat_position = heaters[j]
var reduce = Math.abs(house_position - heat_position)
r = Math.min(r,reduce)
}
max = Math.max(r,max)
}
return max
};In this case, we can also use the dichotomy method to find the heater
var findRadius = function(houses, heaters) {
var r = 0 for(let i = 0 ; i < houses.length ; i ++) {
var house_position = houses[i]
let left = 0 , right = heaters.length - 1 // Find the heat_position closest to house_position // That is, find the rightmost insertion point of house_position while(left <= right && right < heaters.length) {
let mid = left + Math.floor((right - left) / 2)
var heat_position = heaters[mid]
// If the one found is not greater than, go to the right if(heat_position <= house_position) {
left = mid + 1 } else {
right = mid - 1 }
}
// The insertion point found at this time is not necessarily the closest one. The one on the left is smaller than it, so we need to compare it var R = Math.abs(heaters[right] - house_position)
if(right > 0) {
R = Math.min( Math.abs( heaters[right - 1] - house_position) , R)
}
r = Math.max(r,R)
}
return r
};