题目地址
思路
参考Leetcode官方题解:
官方题解
主要思路是:
先对加热器排序,然后对于每个房间,寻找离他最近的加热器并计算最大距离。
代码实现(C++)
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters)
{
int res=0;
sort(heaters.begin(),heaters.end());
for(auto house : houses)
{
int j=upper_bound(heaters.begin(),heaters.end(),house)-heaters.begin();
int i=j-1;
int rightDistance=j>=heaters.size()? INT_MAX : heaters[j]-house;
int leftDistance=i<0? INT_MAX : house-heaters[i];
int curDistance=min(leftDistance,rightDistance);
res=max(res,curDistance);
}
return res;
}
};
总结
对于二分查找的使用还不是很熟练,要多加练习。