1 问题
冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。
所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。
说明:
给出的房屋和供暖器的数目是非负数且不会超过 25000。
给出的房屋和供暖器的位置均是非负数且不会超过10^9。
只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。
所有供暖器都遵循你的半径标准,加热的半径也一样。
示例 2:
输入: [1,2,3,4],[1,4]
输出: 1
解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/heaters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2 解答
排序后遍历,对每个地点,找离它左边最近(small)、右边最近的供暖处(big),并取其中最近的那个。
#include <algorithm>
// using namespace std;
#include <limits>
#include <iostream>
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
std::sort(houses.begin(),houses.end());
std::sort(heaters.begin(),heaters.end());
int res = 0;
int small = 0;
int big = 0;
for (auto &house : houses){
int r = std::numeric_limits<int>::max();
if(big >= heaters.size()){
r = std::min(r,house-heaters[big-1]);
}
else{
while(big < heaters.size()){
if((heaters[big]-house)>0){
r = std::min(r,heaters[big]-house);
if(house-heaters[small]>=0)
r = std::min(r,house-heaters[small]);
break;
}
else{
r = std::min(r,house-heaters[big]);
small = big;
big += 1;
}
}
}
if(r>res){
res = r;
}
}
return res;
}
};