😕题目描述

😔分析

查询其左右最近的一个供暖器的位置,然后在两个供暖器之间取最小值,所有的房子供暖距离取最大值。
使用一个哈希存储,左侧的小于该位置的取暖器位置,和右侧大于该位置的取暖器位置。

😏答案

  1. func Min(lhs, rhs int) int {
  2. if lhs < rhs {
  3. return lhs
  4. }
  5. return rhs
  6. }
  7. func Max(lhs, rhs int) int {
  8. if lhs > rhs {
  9. return lhs
  10. }
  11. return rhs
  12. }
  13. func findRadius(houses []int, heaters []int) int {
  14. sort.Ints(houses)
  15. sort.Ints(heaters)
  16. left := make(map[int]int)
  17. right := make(map[int]int)
  18. j := -1
  19. for i, _ := range houses {
  20. for j < len(heaters)-1 && heaters[j+1] <= houses[i] {
  21. j++
  22. }
  23. if j == -1 {
  24. left[houses[i]] = -10000000000
  25. } else {
  26. left[houses[i]] = heaters[j]
  27. }
  28. }
  29. j = len(heaters)
  30. for i := len(houses) - 1; i >= 0; i-- {
  31. for j > 0 && heaters[j-1] >= houses[i] {
  32. j--
  33. }
  34. if j == len(heaters) {
  35. right[houses[i]] = 10000000000
  36. } else {
  37. right[houses[i]] = heaters[j]
  38. }
  39. }
  40. res := 0
  41. for _, v := range houses {
  42. temp := Min(v-left[v], right[v]-v)
  43. res = Max(res, temp)
  44. }
  45. return res
  46. }