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;
    }
};
相关推荐
小刘|29 分钟前
《Java 实现希尔排序:原理剖析与代码详解》
java·算法·排序算法
jjyangyou33 分钟前
物联网核心安全系列——物联网安全需求
物联网·算法·安全·嵌入式·产品经理·硬件·产品设计
van叶~1 小时前
算法妙妙屋-------1.递归的深邃回响:二叉树的奇妙剪枝
c++·算法
简简单单做算法1 小时前
基于Retinex算法的图像去雾matlab仿真
算法·matlab·图像去雾·retinex
knighthood20011 小时前
解决:ros进行gazebo仿真,rviz没有显示传感器数据
c++·ubuntu·ros
云卓SKYDROID1 小时前
除草机器人算法以及技术详解!
算法·机器人·科普·高科技·云卓科技·算法技术
半盏茶香1 小时前
【C语言】分支和循环详解(下)猜数字游戏
c语言·开发语言·c++·算法·游戏
徐子童2 小时前
双指针算法习题解答
算法
小堇不是码农2 小时前
在VScode中配置C_C++环境
c语言·c++·vscode
Jack黄从零学c++2 小时前
C++ 的异常处理详解
c++·经验分享