zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 475 供暖器

    475. 供暖器

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

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

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

    说明:

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

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

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

    class Solution {
        public int findRadius(int[] houses, int[] heaters) {
       // 先进行升序排列
            Arrays.sort(houses);
            Arrays.sort(heaters);
            int radius = 0;
            int i = 0;
            for (int house : houses) {
                while (i < heaters.length && heaters[i] < house) {
                    // 一直找到处于房屋右侧的热水器
                    i++;
                }
                if (i == 0)
                    radius = Math.max(radius, heaters[i] - house);
                else if (i == heaters.length)
                    // 最后一个热水器
                    return Math.max(radius, houses[houses.length-1] - heaters[heaters.length-1]);
                else
                    // 房屋右侧的热水器和房屋左侧的热水器,取小的那个
                    radius = Math.max(radius, Math.min(heaters[i] - house, house - heaters[i - 1]));
            }
            return radius;
        }
    }
    
  • 相关阅读:
    ueditor1.4.3.all.js报错
    ueditor中FileUtils.getTempDirectory()找不到
    java后台验证码的生成
    applicationContext.xml重要配置
    Java代码实现文件上传(转载)
    jquery动态实现填充下拉框
    POI写入word docx 07 的两种方法
    POI读word docx 07 文件的两种方法
    POI转换word doc文件为(html,xml,txt)
    Linux中zip压缩和unzip解压缩命令详解
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946447.html
Copyright © 2011-2022 走看看