475. 供暖器 [中等]

135 阅读2分钟

题目

冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。

在加热器的加热半径范围内的每个房屋都可以获得供暖。

现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置,请你找出并返回可以覆盖所有房屋的最小加热半径。

说明:所有供暖器都遵循你的半径标准,加热的半径也一样。

示例 1:

输入: houses = [1,2,3], heaters = [2]

输出: 1

解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。

示例 2:

输入: houses = [1,2,3,4], heaters = [1,4]

输出: 1

解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。

示例 3:

输入:houses = [1,5], heaters = [2]

输出:3

提示:

  • 1 <= houses.length, heaters.length <= 3 * 104
  • 1 <= houses[i], heaters[i] <= 109

来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/he…

思路

房间的左右两侧都可能存在暖气片,左右两边的距离最小值作为最小半径。一些房间,可能不存在暖气片,那么可以定义为距离左边的暖气片 巨远;一些房间,可能不存在右边的暖气片,那么可以定义为距离右边的暖气片巨远。

最后取这些最小半径的最大值。

关键点在于:找到该房间最左侧的暖气片,也就是找到小于等于某个值的最大值。

代码

class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(heaters);
        int max = Integer.MIN_VALUE;
        for (int house : houses) {
            int index = findMin(heaters, house);
            // 这个地方写的很赞!
            int leftDis = index < 0 ? Integer.MAX_VALUE : house - heaters[index];
            int rightDis = index + 1 >= heaters.length ? Integer.MAX_VALUE : heaters[index + 1] - house;
            int distance = Math.min(leftDis, rightDis);
            max = Math.max(distance, max);
        }
        return max;
    }

    int findMin(int[] heaters, int target) {
        int low = 0;
        int high = heaters.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (heaters[mid] == target) {
                return mid;
            } else if (heaters[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return low - 1;
    }
}