475. Heaters (Easy)
Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.
Note:
- Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
- Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
- As long as a house is in the heaters' warm radius range, it can be warmed.
- All the heaters follow your radius standard and the warm radius will the same.
Example 1:
Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
Example 2:
Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
Solution: Binary Search
这道题是一道蛮有意思的题目,首先我们看题目中的例子,不管是houses还是heaters数组都是有序的,所以我们也需要给输入的这两个数组先排序,以免其为乱序。我们就拿第二个例子来分析,我们的目标是houses中的每一个数字都要被cover到,那么我们就遍历houses数组,对每一个数组的数字,我们在heaters中找能包含这个数字的左右范围,然后看离左右两边谁近取谁的值,如果某个house位置比heaters中最小的数字还小,那么肯定要用最小的heater去cover,反之如果比最大的数字还大,就用最大的数字去cover。对于每个数字算出的半径,我们要取其中最大的值。通过上面的分析,我们就不难写出代码了,我们在heater中两个数一组进行检查,如果后面一个数和当前house位置差的绝对值小于等于前面一个数和当前house位置差的绝对值,那么我们继续遍历下一个位置的数。跳出循环的条件是遍历到heater中最后一个数,或者上面的小于等于不成立,此时heater中的值和当前house位置的差的绝对值就是能cover当前house的最小半径,我们更新结果res即可,参见代码如下:
version 1: TLE
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
int i = 0, res = 0;
for (int h:houses) {
auto larger = lower_bound(heaters.begin(), heaters.end(), h);
int curRadius = INT_MAX;
if (larger != heaters.end()) {
curRadius = *larger-h;
}
if (larger != heaters.begin()) {
auto smaller = larger-1;
curRadius = min(curRadius, h-*smaller);
}
res = max(res, curRadius);
}
return res;
}
};
version 2: 1052ms
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
int n = heaters.size(), i = 0, res = 0;
for (int h:houses) {
while (i < n-1 && abs(heaters[i] - h) >= abs(heaters[i+1] - h)) ++i;
res = max(res, abs(heaters[i] - h));
}
return res;
}
};