当前位置:网站首页>【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)。
边栏推荐
猜你喜欢

A brief analysis of mobile APP security testing in software testing, shared by a third-party software testing agency in Beijing

Flink Yarn Per Job - Yarn应用

Deep Learning Fundamentals - Numpy-based Recurrent Neural Network (RNN) implementation and backpropagation training

Quartus 使用 tcl 文件快速配置管脚

Docker实践经验:Docker 上部署 mysql8 主从复制

sys_kill system call

Secondary Vocational Network Security Competition B7 Competition Deployment Process

【C语言进阶】文件操作(二)

12306抢票,极限并发带来的思考?

GIF制作-灰常简单的一键动图工具
随机推荐
程序员还差对象?new一个就行了
Several interview questions about golang concurrency
Sql之各种Join
切面打印调取的方法
在MySQL中使用MD5加密【入门体验】
【MySQL篇】初识数据库
Special characters & escapes in bat
软件测试之移动APP安全测试简析,北京第三方软件检测机构分享
UI自动化测试框架搭建-标记性能较差用例
【MySQL系列】MySQL数据库基础
数据机构---第五章树与二叉树---二叉树的概念---应用题
async和await用法介绍
windows sql server 如何卸载干净?
伸展树的特性及实现
cdh6打开oozieWeb页面,Oozie web console is disabled.
Department project source code sharing
Loading configuration of Nacos configuration center
numpy.hstack
oozie startup error on cdh's hue, Cannot allocate containers as requested resource is greater than maximum allowed
Chapter 19 Tips and Traps: Common Goofs for Novices