当前位置:网站首页>【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)。
边栏推荐
猜你喜欢
Use Jenkins for continuous integration, this knowledge point must be mastered
Docker实践经验:Docker 上部署 mysql8 主从复制
20220725 Information update
Thinkphp 5.0.24变量覆盖漏洞导致RCE分析
cdh的hue上oozie启动报错,Cannot allocate containers as requested resource is greater than maximum allowed
20220725资料更新
Flink Yarn Per Job - 提交流程一
nodejs--process
月薪12K,蝶变向新,勇往直前—她通过转行测试实现月薪翻倍~
深度学习基础-基于Numpy的循环神经网络(RNN)实现和反向传播训练
随机推荐
6132. All the elements in the array is equal to zero - quick sort method
FAST-LIO2 code analysis (2)
Bean的生命周期
6134. Find the closest node to the given two nodes - force double hundred code
【MySQL系列】MySQL索引事务
Chapter 12 End-User Task As Shell Scripts
Programmer is still short of objects? A new one is enough
颜色透明参数
YOLO等目标检测模型的非极大值抑制NMS和评价指标(Acc, Precision, Recall, AP, mAP, RoI)、YOLOv5中[email protected]与
Data Organization --- Chapter 5 Trees and Binary Trees --- The Concept of Binary Trees --- Application Questions
Always use "noopener" or "noreferrer" for links that open in a new tab
【MySQL系列】MySQL数据库基础
PostgreSQL Basics--Common Commands
【图像融合】基于加权和金字塔实现图像融合附matlab代码
Dynamic Scene Deblurring with Parameter Selective Sharing and Nested Skip Connections
Use Jenkins for continuous integration, this knowledge point must be mastered
Solve the port to take up
架构基本概念和架构本质
How to better understand and do a good job?
使用Jenkins做持续集成,这个知识点必须要掌握