475-供暖器

463-岛屿的周长

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

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

所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。

说明:

  1. 给出的房屋和供暖器的数目是非负数且不会超过 25000。
  2. 给出的房屋和供暖器的位置均是非负数且不会超过10^9。
  3. 只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。
  4. 所有供暖器都遵循你的半径标准,加热的半径也一样。

示例 1:

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

示例 2:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/heaters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    public int findRadius(int[] houses, int[] heaters) {
        // 对于每个房屋,要么用前面的暖气,要么用后面的,二者取近的,得到距离;
        // 对于所有的房屋,选择最大的上述距离。
        Arrays.sort(houses);
        Arrays.sort(heaters);
        int res = Integer.MIN_VALUE;
        int i = 0;
        for (int house : houses) {
            int min;
            while (i < heaters.length && house > heaters[i]) {
                i++;
            }
            if (i == 0) {
                min = heaters[0] - house;
            } else if (i < heaters.length) {
                min = Math.min(heaters[i] - house, house - heaters[i - 1]);
            } else {
                min = Math.abs(heaters[i - 1] - house);
            }
            res = Math.max(res, min);
        }
        return res;
    }

猜你喜欢

转载自www.cnblogs.com/angelica-duhurica/p/12215332.html