475. 供暖器

看了题解之后在纸上画了画才写出来的。可以假设对于每个house左右都有加热器,那么这个house的半径就是min(左加热器,右加热器)。ans则是所有house半径的最大值。

初始化ans为0。将heaters从小到大排序,遍历houses,对于houses中的每个house,找到第1个大于house的位置:

1. 如果这个位置index等于0,说明heater的第1个数就大于house =>这个house就只有这1个加热器(右加热器),这个半径就等于heaters[0]-house,计算ans = max(ans, 这个半径)

2. 如果这个位置index等于heaters.size(),说明找到最后也没有在heaters中找到大于house的heater =>这个house就只有最后一个加热器离它最近(左加热器),这个半径就等于house-heaters[index-1],取ans和这个半径的最大值

3. 然后就是一般情况,house的右边加热器为heaters[index],house左边的加热器为heaters[index-1],这个house的最小半径就是min(rightval-house, house-leftval),这个最小半径和ans取最大值。

4. 最后返回ans即可

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        sort(heaters.begin(),heaters.end());
        int ans = 0;
        for (int house:houses){
            // 在heaters中查找第1个大于house的位置
            int uppos = upper_bound(heaters.begin(),heaters.end(),house) - heaters.begin();
            if (uppos ==0 ){
                // 只有一个加热器
                ans = max(ans,heaters[uppos]-house);
            }
             else if (uppos == heaters.size()){
                ans = max(ans,house - heaters[uppos-1]);
            }
            else{
                // 有2个加热器
                int lowpos = uppos-1;
                int tmpans = min(house-heaters[lowpos],heaters[uppos]-house);
                ans = max(ans,tmpans);
            }
        }
        return ans;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值