供暖器

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

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

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

说明:

  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,这样所有房屋就都能得到供暖。

 

https://leetcode-cn.com/problems/heaters/description/

 

class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(houses);
        Arrays.sort(heaters);
        int maxLen = 0;
        int heaterIndex = 0;
        int houseIndex = 0;
        while (heaterIndex < heaters.length && houseIndex < houses.length) {
            if (heaters[heaterIndex] > houses[houseIndex]) {
                if (heaterIndex != 0) {
                    //找出房屋左右最近的供暖机的最小距离
                    int dis = Math.min((heaters[heaterIndex] - houses[houseIndex]), (houses[houseIndex] - heaters[heaterIndex - 1]));
                    maxLen = Math.max(maxLen, dis);
                } else {
                    //若是房屋左边没有供暖机
                    maxLen = Math.max(maxLen, heaters[heaterIndex] - houses[houseIndex]);
                }
                //下一个房屋
                houseIndex++;
            } else {
                //下一个供暖机
                heaterIndex++;
            }
        }
        //供暖机已经遍历到尽头了,房子仍没有遍历完
        if (heaterIndex == heaters.length) {
            //最后一个房子到最后一个供暖机的距离
            int dis = houses[houses.length - 1] - heaters[heaterIndex - 1];
            maxLen = Math.max(maxLen, dis);
        }
        return maxLen;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值