LeetCode475. Heaters

文章目录

一、题目

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

Every house can be warmed, as long as the house is within the heater's warm radius range.

Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.

Notice that all the heaters follow your radius standard, and the warm radius will the same.

Example 1:

Input: houses = [1,2,3], heaters = [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.

Example 2:

Input: houses = [1,2,3,4], heaters = [1,4]

Output: 1

Explanation: The two heaters were placed at positions 1 and 4. We need to use a radius 1 standard, then all the houses can be warmed.

Example 3:

Input: houses = [1,5], heaters = [2]

Output: 3

Constraints:

1 <= houses.length, heaters.length <= 3 * 104

1 <= houses[i], heaters[i] <= 109

二、题解

双指针,i和j分别从houses和heaters的索引从左向右移动。

cpp 复制代码
class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        sort(houses.begin(),houses.end());
        sort(heaters.begin(),heaters.end());
        int res = 0;
        for(int i = 0,j = 0;i < houses.size();i++){
            while(!best(houses,heaters,i,j)) j++;
            res = max(res,abs(houses[i]-heaters[j]));
        }
        return res;
    }
    bool best(vector<int>& houses,vector<int>& heaters,int i,int j){
        if(j == heaters.size() - 1) return true;
        else if(abs(houses[i]-heaters[j]) < abs(houses[i]-heaters[j + 1])) return true;
        else return false;
    }
};
相关推荐
云深处@24 分钟前
【C++11】特殊类&&单例模式
开发语言·c++
小程故事多_8024 分钟前
RAG,基于字号频率的内容切分算法,非常强
人工智能·算法·aigc
ADDDDDD_Trouvaille27 分钟前
2026.2.15——OJ83-85题
c++·算法
烟花落o30 分钟前
算法的时间复杂度和空间复杂度
开发语言·数据结构·笔记·算法
蒟蒻小袁30 分钟前
力扣hot-100(一刷自用版)
leetcode·哈希算法·散列表
Ronaldinho Gaúch1 小时前
算法题中的日期问题
开发语言·c++·算法
踩坑记录1 小时前
leetcode ho100 124. 二叉树中的最大路径和 hard
leetcode
Chary20161 小时前
Opencascade VTK 集成服务 VIS
算法
楠秋9202 小时前
代码随想录算法训练营第三十一天|56. 合并区间 、 738.单调递增的数字、968.监控二叉树
数据结构·算法·leetcode·贪心算法
zenpluck2 小时前
RTAB-Map学习记录(1)--论文阅读
c++·论文阅读·学习·机器人