思路:寻找每个房子左边最近的供暖器和右边最近的供暖器,最后的答案就是每个房子离其最近的供暖器的距离的最大值
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
int l1,l2;
l1 = houses.size();
l2 = heaters.size();
vector <int> left;
vector <int> right;
int cnt = 0;
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
for(int i = 0; i < l1; i++){
right.push_back(0);
left.push_back(0);
}
for(int i = 0; i < l1; i++){
if(houses[i] < heaters[cnt]){
left[i] = INT_MAX;
}else if(cnt == l2 - 1){
left[i] = abs(houses[i] - heaters[cnt]);
}else{
while(houses[i] >= heaters[cnt + 1]){
cnt++;
if(cnt == l2 - 1){
break;
}
}
left[i] = abs(houses[i] - heaters[cnt]);
}
}
cnt = l2 - 1;
for(int i = l1 - 1; i >= 0; i--){
if(houses[i] > heaters[cnt]){
right[i] = INT_MAX;
}else if(cnt == 0){
right[i] = abs(houses[i] - heaters[cnt]);
}else{
while(houses[i] <= heaters[cnt - 1]){
cnt--;
if(cnt == 0){
break;
}
}
right[i] = abs(houses[i] - heaters[cnt]);
}
}
int an = INT_MIN;
for(int i = 0; i < l1; i++){
int minDis = min(left[i], right[i]);
// cout << left[i] << " " << right[i] << endl;
an = max(minDis, an);
}
return an;
}
};