Golang leetcode 475. Heaters.go

时间:2022-06-19
本文章向大家介绍Golang leetcode 475. Heaters.go,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89175256

思路

用二分查找。对heaters进行sort,然后得到某个house的相对位置。再计算左右的距离。

code

func findRadius(houses []int, heaters []int) int {
	sort.Ints(heaters)
	ret := -1
	for _, house := range houses {
		idx := sort.SearchInts(heaters, house)
		l, r := math.MaxInt32, math.MaxInt32
		if idx-1 >= 0 {
			l = house - heaters[idx-1]
		}
		if idx < len(heaters) {
			r = heaters[idx] - house
		}
		ret = mymax(ret, mymin(l, r))
	}
	return ret
}
func mymax(x, y int) int {
	if x > y {
		return x
	}
	return y
}
func mymin(x, y int) int {
	if x > y {
		return y
	}
	return x
}