当前位置:网站首页>【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)。
边栏推荐
- 高效工作文档产出归类
- Calculate the distance between two points
- 数据机构---第五章树与二叉树---二叉树的概念---应用题
- 6132. All the elements in the array is equal to zero - quick sort method
- 使用Ganache、web3.js和remix在私有链上部署并调用合约
- 几道关于golang并发的面试题
- Flink Yarn Per Job - Yarn应用
- solidity
- 深度学习基础-基于Numpy的循环神经网络(RNN)实现和反向传播训练
- DRF generating serialization class code
猜你喜欢

Architecture basic concept and nature of architecture

在CentOS下安装MySQL

A brief analysis of mobile APP security testing in software testing, shared by a third-party software testing agency in Beijing
![[C language advanced] file operation (2)](/img/4d/49d9603aeed16f1600d69179477eb3.png)
[C language advanced] file operation (2)

20220725 Information update

Chrome书签插件,让你实现高效整理

多御安全浏览器android版更新至1.7,改进加密协议

sys_kill系统调用

2022 6th Strong Net Cup Part WP

月薪12K,蝶变向新,勇往直前—她通过转行测试实现月薪翻倍~
随机推荐
颜色透明参数
数据机构---第五章树与二叉树---二叉树的概念---应用题
12306抢票,极限并发带来的思考?
尚硅谷MySQL学习笔记
[C language advanced] file operation (2)
Docker实践经验:Docker 上部署 mysql8 主从复制
color transparency parameter
An interview question about iota in golang
Enterprise firewall management, what firewall management tools are there?
cdh6 opens oozieWeb page, Oozie web console is disabled.
cmd command
numpy.hstack
Thymeleaf简介
【MySQL系列】 MySQL表的增删改查(进阶)
Deep Learning Fundamentals - Numpy-based Recurrent Neural Network (RNN) implementation and backpropagation training
在MySQL登录时出现Access denied for user ‘root‘@‘localhost‘ (using password YES) 拒绝访问问题解决
Quartus 使用 tcl 文件快速配置管脚
@Resource和@Autowired的区别
The third chapter of the imitation cattle network project: develop the core functions of the community (detailed steps and ideas)
1个月写900多条用例,二线城市年薪33W+的测试经理能有多卷?