[leetcode]475. Heaters

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Example 1:

Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

分析:

给定两个数组,一个表示房屋的位置,一个表示供暖器的位置,房屋和供暖器在同一水平线上,要求能覆盖所有房屋的供暖器的最短半径。遍历houses数组,对每一个数字,在heaters中找能包含这个数字的左右范围,然后取离左右两边近的值,如果某个house位置比heaters中最小的数字还小,那么用最小的heater去覆盖,反之如果比最大的数字还大,就用最大的数字去覆盖。对于每个数字算出的半径,取其中最大的值即可。

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        int len1 = houses.size();
        int len2 = heaters.size();
        int j = 0;
        int res = 0;
        sort(houses.begin() , houses.end());
        sort(heaters.begin() , heaters.end());
        for(int i = 0; i < len1; i++)
        {
            int cur = houses[i];
            while(j < len2-1 && abs(heaters[j+1]-cur) <= abs(heaters[j]-cur))
                j++;
            res = max(res , abs(heaters[j]-cur));
        }
        return res;        
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值