【LeetCode每日一题】475. 供暖器【中等】

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

在加热器的加热半径范围内的每个房屋都可以获得供暖。

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

说明:所有供暖器都遵循你的半径标准,加热的半径也一样。

 

示例 1:

输入: houses = [1,2,3], heaters = [2] 输出: 1 解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。 示例 2:

输入: houses = [1,2,3,4], heaters = [1,4] 输出: 1 解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。 示例 3:

输入:houses = [1,5], heaters = [2] 输出:3  

提示:

1 <= houses.length, heaters.length <= 3 * 104 1 <= houses[i], heaters[i] <= 109

题解: 看到这题就想到二分查找了,可以对heaters进行排序,然后对每一个房屋二分查找两端最近的heaters,取一个最小值,将这些最小值汇总起来取一个最大值,就是答案。

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        sort(heaters.begin(), heaters.end());
        int ans = 0;

        function<int(int, int, int)> binarySearch = [&](int l, int r, int e){
            while(l < r){
                int m = l + (r - l) / 2;
                if(heaters[m] >= e){
                    r = m;
                }
                else l = m + 1;
            }
            return l;
        };

        for(int i = 0; i < houses.size(); i++){
            int pos = binarySearch(0, heaters.size() - 1, houses[i]);
            int dis = 0x3f3f3f3f;
            if(pos > 0) dis = abs(houses[i] - heaters[pos - 1]);
            //if(pos > 0)cout<<"dis1:"<<abs(houses[i] - heaters[pos - 1])<<endl;
            dis = min(dis, abs(heaters[pos] - houses[i]));
            //cout<<"dis2:"<<dis<<endl;
            ans = max(ans, dis);
        }
        return ans;
    }
};

还有一种双指针的做法。

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        sort(houses.begin(), houses.end());
        sort(heaters.begin(), heaters.end());
        int ans = 0;
        for (int i = 0, j = 0; i < houses.size(); i++) {
            int curDistance = abs(houses[i] - heaters[j]);
            while (j < heaters.size() - 1 && abs(houses[i] - heaters[j]) >= abs(houses[i] - heaters[j + 1])) {
                j++;
                curDistance = min(curDistance, abs(houses[i] - heaters[j]));
            }
            ans = max(ans, curDistance);
        }
        return ans;
    }
};
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务