1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
int findRadius(vector<int> &houses, vector<int> &heaters) {
sort(heaters.begin(), heaters.end());
sort(houses.begin(), houses.end());
int ans = 0;
for (int house: houses) {
// 找到比该房间右边的第一个暖气的索引
int currentRightHeater = upper_bound(heaters.begin(), heaters.end(), house) - heaters.begin();
int currentLeftHeater = currentRightHeater - 1;
int rightDistance = currentRightHeater >= heaters.size() ? INT_MAX : heaters[currentRightHeater] - house;
int leftDistance = currentLeftHeater < 0 ? INT_MAX : house - heaters[currentLeftHeater];
// 他要用最近的一个这样才能保证最小,
int curDistance = min(leftDistance, rightDistance);
// 在所有的房屋都要满足要求,则要取最大的一个
ans = max(ans, curDistance);
}
return ans;
}
|