[leetcode]475. Heaters

[leetcode]475. Heaters


Analysis

ummmm~—— [ummmm~]

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.
分别对两个数组进行排序,然后寻找距离每个house最近的加热器,不断更新结果就行了。

Implement

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/80830500