lintcode 1219. 加热器

冬天来啦!你的任务是设计出一个具有固定加热半径的加热器,使得所有房屋在这个冬天不至于太冷。

现在你能够获知所有房屋和加热器所处的位置,它们均分布在一条水平线中。你需要找出最小的加热半径使得所有房屋都处在至少一个加热器的加热范围内。

所以,你的输入将会是所有房屋和加热器所处的位置,期望输出为加热器最小的加热半径。

样例
样例1:

输入:[1,2,3],[2]
输出:1
说明:唯一的一个加热器被放在2的位置,那么只要加热半径为1,就能覆盖到所有房屋了。
样例2:

输入:[1,2,3,4],[1,4]
输出:1
说明:两个加热器分别位于14,只需要加热半径为1,就能加热所有房屋了。
注意事项
房屋和加热器的数目均为非负整数,并且它们不会超过25000。
房屋和加热器的位置均为非负整数,并且它们不会超过10^9。
只要一间房屋位于加热器的加热半径内(包括边界),它就会被加热。
所有加热器的加热半径相同。
class Solution {
public:
    /**
     * @param houses: positions of houses
     * @param heaters: positions of heaters
     * @return: the minimum radius standard of heaters
     */
    int findRadius(vector<int> &houses, vector<int> &heaters) {
        // Write your code here
        vector<int> dis;
        sort(houses.begin(),houses.end());
        sort(heaters.begin(),heaters.end());
        int ptr = 0;
        int res = 0;
        int dist;
        for(int i=0;i<houses.size();i++){
            while(heaters[ptr]<houses[i]&&ptr<heaters.size()-1) ptr++;
            if(ptr==0) dist = abs(heaters[ptr]-houses[i]);
            else dist = min(abs(houses[i]-heaters[ptr-1]),abs(heaters[ptr]-houses[i]));
            res = max(res,dist);
        }
        return res;
    }
};
发布了330 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/103941502