0
点赞
收藏
分享

微信扫一扫

【LeetCode】475. 供暖器

承蒙不弃 2022-01-18 阅读 21

文章目录

题目:475. 供暖器

475. 供暖器

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

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

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

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

示例 1:

示例 2:

示例 3:

提示:

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

解题思路

  1. 对houses和heaters排序
  2. 遍历houses
    1. 得到houses[i]heaters[j]相减的绝对值curD;
    2. 如果当前curD大于与下一个heater相减的绝对值,不断后移,每次curD等于二者最小值
    3. res等于res和curD的最大值

代码

class Solution {
public:
// 1. 对houses和heaters排序
// 2. 遍历houses
// 	1. 得到`houses[i]`和`heaters[j]`相减的绝对值curD;
// 	2. 如果当前curD大于与下一个heater相减的绝对值,不断后移,每次curD等于二者最小值
// 	3. res等于res和curD的最大值
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        int res = 0;
        sort(houses.begin(), houses.end());
        sort(heaters.begin(),heaters.end());

        for (int i = 0, j = 0; i < houses.size(); i++) {
            int curD = abs(houses[i] - heaters[j]);
            while (j < heaters.size() - 1 && curD >= abs(houses[i] - heaters[j + 1])) {
                j++;
                curD = min(curD, abs(houses[i] - heaters[j]));
            }
            res = max(res, curD);
        }
        return res;
    }
};
举报

相关推荐

0 条评论