😕题目描述
😔分析
查询其左右最近的一个供暖器的位置,然后在两个供暖器之间取最小值,所有的房子供暖距离取最大值。
使用一个哈希存储,左侧的小于该位置的取暖器位置,和右侧大于该位置的取暖器位置。
😏答案
func Min(lhs, rhs int) int {if lhs < rhs {return lhs}return rhs}func Max(lhs, rhs int) int {if lhs > rhs {return lhs}return rhs}func findRadius(houses []int, heaters []int) int {sort.Ints(houses)sort.Ints(heaters)left := make(map[int]int)right := make(map[int]int)j := -1for i, _ := range houses {for j < len(heaters)-1 && heaters[j+1] <= houses[i] {j++}if j == -1 {left[houses[i]] = -10000000000} else {left[houses[i]] = heaters[j]}}j = len(heaters)for i := len(houses) - 1; i >= 0; i-- {for j > 0 && heaters[j-1] >= houses[i] {j--}if j == len(heaters) {right[houses[i]] = 10000000000} else {right[houses[i]] = heaters[j]}}res := 0for _, v := range houses {temp := Min(v-left[v], right[v]-v)res = Max(res, temp)}return res}
