当前位置:网站首页>【Leetcode】475. Heaters
【Leetcode】475. Heaters
2022-08-01 23:47:00 【记录算法题解】
题目地址:
https://leetcode.com/problems/heaters/description/
给定两个数组 A A A和 B B B,分别代表房屋的坐标和加热器的坐标,每个加热器 B [ i ] B[i] B[i]能加热的范围为 [ B [ i ] − x , B [ i ] + x ] [B[i]-x,B[i]+x] [B[i]−x,B[i]+x], x x x对于所有加热器都是一样的。问半径最小是多少能使得所有房屋都能被加热。
可以二分答案,然后用双指针(假设两个数组都排好了序,那么可以关注每个加热器可以加热到的最后一个房屋,这个下标一定是单调增的)。代码如下:
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
int l = 0, r = max(heaters[0] - houses[0], houses.back() - heaters[0]);
while (l < r) {
int mid = l + (r - l >> 1);
if (check(mid, houses, heaters)) r = mid;
else l = mid + 1;
}
return l;
}
bool check(int len, vector<int>& ho, vector<int>& he) {
for (int i = 0, j = 0; i < he.size(); i++) {
if (ho[j] < he[i] - len) return false;
while (j < ho.size() && abs(ho[j] - he[i]) <= len) j++;
if (j == ho.size()) return true;
}
return false;
}
};
时间复杂度 O ( l A log l A + l B log l B + ( l A + l B ) log max { B [ 0 ] − A [ 0 ] , B [ l B − 1 ] − A [ 0 ] } ) O(l_A\log l_A+l_B\log l_B+(l_A+l_B)\log \max\{B[0]-A[0], B[l_B-1]-A[0]\}) O(lAloglA+lBloglB+(lA+lB)logmax{ B[0]−A[0],B[lB−1]−A[0]}),空间 O ( 1 ) O(1) O(1)。
边栏推荐
猜你喜欢

Architecture basic concept and nature of architecture

Artifact XXXwar exploded Artifact is being deployed, please wait...(已解决)

TexturePacker使用文档
![Thesis understanding [RL - Exp Replay] - Experience Replay with Likelihood-free Importance Weights](/img/f1/9824f32dd4fe4b3e94af3f945b1801.png)
Thesis understanding [RL - Exp Replay] - Experience Replay with Likelihood-free Importance Weights

async和await用法介绍

sys_kill system call

Work for 5 years, test case design is bad?To look at the big case design summary

在MySQL登录时出现Access denied for user ‘root‘@‘localhost‘ (using password YES) 拒绝访问问题解决

nodejs--process

ICLR 2022最佳论文:基于对比消歧的偏标签学习
随机推荐
一道golang中关于iota的面试题
6134. Find the closest node to the given two nodes - force double hundred code
使用Ganache、web3.js和remix在私有链上部署并调用合约
PostgreSQL Basics--Common Commands
数据机构---第五章树与二叉树---二叉树的概念---应用题
如何进行数据库备份
Spark Sql之join on and和where
ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation
如何更好的理解的和做好工作?
【MySQL系列】 MySQL表的增删改查(进阶)
几道关于golang并发的面试题
Calculate the midpoint between two points
Several interview questions about golang concurrency
numpy.where
Chapter 11 Working with Dates and Times
仿牛客网项目第三章:开发社区核心功能(详细步骤和思路)
Bean的生命周期
Artifact XXXwar exploded Artifact is being deployed, please wait...(已解决)
Docker实践经验:Docker 上部署 mysql8 主从复制
Work for 5 years, test case design is bad?To look at the big case design summary