475.heaters.go 633 B

12345678910111213141516171819202122232425262728293031323334353637
  1. func findRadius(houses []int, heaters []int) (radius int) {
  2. sort.Ints(heaters)
  3. n := len(heaters)
  4. for _, i := range houses {
  5. beg, end := 0, n-1
  6. for beg <= end {
  7. mid := beg + (end-beg)/2
  8. if heaters[mid] < i {
  9. beg = mid + 1
  10. } else {
  11. end = mid - 1
  12. }
  13. }
  14. if beg == 0 {
  15. radius = maxInt(radius, heaters[beg]-i)
  16. } else if beg == n {
  17. radius = maxInt(radius, i-heaters[n-1])
  18. } else {
  19. radius = maxInt(radius, minInt(i-heaters[beg-1], heaters[beg]-i))
  20. }
  21. }
  22. return
  23. }
  24. func minInt(x, y int) int {
  25. if x < y {
  26. return x
  27. }
  28. return y
  29. }
  30. func maxInt(x, y int) int {
  31. if x < y {
  32. return y
  33. }
  34. return x
  35. }