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;
    }
};
相关推荐
D_FW几秒前
数据结构第一章:绪论
数据结构·考研
苦藤新鸡1 分钟前
2.字母异位词分组
c语言·c++·力扣·哈希算法
ysn111113 分钟前
简单多边形三角剖分---耳切法(含源码)
算法
e疗AI产品之路4 分钟前
一文介绍Philips DXL心电图算法
算法·pan-tompkins·心电分析
YGGP10 分钟前
【Golang】LeetCode 21. 合并两个有序链表
leetcode·链表·golang
小袁顶风作案14 分钟前
leetcode力扣——135.分发糖果
算法·leetcode·职场和发展
于齐龙16 分钟前
2025年12月24日 - 数据结构
数据结构
AAA.建材批发刘哥18 分钟前
02--C++ 类和对象上篇
开发语言·c++
橘颂TA24 分钟前
【Linux】从 “抢资源” 到 “优雅控场”:Linux 互斥锁的原理与 C++ RAII 封装实战(Ⅰ)
linux·运维·服务器·c++·算法