Heaters LeetCode solution in C++

1
class Solution {
2
public:
3
// we will assign each house to its closest heater in position(by taking the
4
// minimum of the distance between the two closest heaters to the house) and
5
// then store the maximum of these differences(since we want to have the same
6
// standard radius)
7
int findRadius(vector<int> &houses, vector<int> &heaters) {
8
sort(heaters.begin(), heaters.end());
9
int radius = 0;
10
for (int house : houses) {
11
// finding the smallest heater whose position is not greater than
12
// the current house
13
int index = lower_bound(heaters.begin(), heaters.end(), house) - heaters.begin();
14
if (index == heaters.size()) {
15
index--;
16
}
17
// the two closest positions to house will be heaters[index] and
18
// heaters[index-1]
19
int leftDiff = (index - 1 >= 0) ? abs(house - heaters[index - 1]) : INT_MAX;
20
int rightDiff = abs(house - heaters[index]);
21
radius = max(radius, min(leftDiff, rightDiff));
22
}
23
return radius;
24
}
25
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0