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;
    }
};
相关推荐
子豪-中国机器人几秒前
枚举算法和排序算法能力测试
开发语言·c++·算法
qiuyunoqy1 分钟前
基础算法之二分算法 --- 2
算法
1白天的黑夜112 分钟前
栈-844.比较含退格的字符串-力扣(LeetCode)
c++·leetcode·
重生之我是Java开发战士13 分钟前
【数据结构】Java集合框架:List与ArrayList
java·数据结构·list
爱干饭的boy29 分钟前
手写Spring底层机制的实现【初始化IOC容器+依赖注入+BeanPostProcesson机制+AOP】
java·数据结构·后端·算法·spring
二哈不在线39 分钟前
代码随想录二刷之“动态规划”~GO
算法·golang·动态规划
cellurw1 小时前
俄罗斯方块终端游戏实现 —— C语言系统编程与终端控制
c语言·算法
躲在云朵里`1 小时前
Redis深度解析:核心数据结构、线程模型与高频面试题
数据结构·数据库·redis
林夕忆梦_猫1 小时前
初识C++
开发语言·c++
chxin140161 小时前
openCV3.0 C++ 学习笔记补充(自用 代码+注释)---持续更新 四(91-)
c++·opencv·计算机视觉