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.
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.
分析:
给定两个数组,一个表示房屋的位置,一个表示供暖器的位置,房屋和供暖器在同一水平线上,要求能覆盖所有房屋的供暖器的最短半径。遍历houses数组,对每一个数字,在heaters中找能包含这个数字的左右范围,然后取离左右两边近的值,如果某个house位置比heaters中最小的数字还小,那么用最小的heater去覆盖,反之如果比最大的数字还大,就用最大的数字去覆盖。对于每个数字算出的半径,取其中最大的值即可。
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
int len1 = houses.size();
int len2 = heaters.size();
int j = 0;
int res = 0;
sort(houses.begin() , houses.end());
sort(heaters.begin() , heaters.end());
for(int i = 0; i < len1; i++)
{
int cur = houses[i];
while(j < len2-1 && abs(heaters[j+1]-cur) <= abs(heaters[j]-cur))
j++;
res = max(res , abs(heaters[j]-cur));
}
return res;
}
};