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;
    }
};
相关推荐
SummerGao.几秒前
Windows 快速搭建C++开发环境,安装C++、CMake、QT、Visual Studio、Setup Factory
c++·windows·qt·cmake·visual studio·setup factory
查理零世5 分钟前
【蓝桥杯集训·每日一题2025】 AcWing 6134. 哞叫时间II python
python·算法·蓝桥杯
仟濹5 分钟前
【二分搜索 C/C++】洛谷 P1873 EKO / 砍树
c语言·c++·算法
紫雾凌寒14 分钟前
解锁机器学习核心算法|神经网络:AI 领域的 “超级引擎”
人工智能·python·神经网络·算法·机器学习·卷积神经网络
YH_DevJourney36 分钟前
Linux-C/C++《C/8、系统信息与系统资源》
linux·c语言·c++
京东零售技术38 分钟前
AI Agent实战:打造京东广告主的超级助手 | 京东零售技术实践
算法
Igallta_8136222 小时前
【小游戏】C++控制台版本俄罗斯轮盘赌
c语言·开发语言·c++·windows·游戏·游戏程序
且听风吟ayan2 小时前
leetcode day19 844+977
leetcode·c#
MiyamiKK572 小时前
leetcode_位运算 190.颠倒二进制位
python·算法·leetcode
C137的本贾尼2 小时前
解决 LeetCode 串联所有单词的子串问题
算法·leetcode·c#