475 Heaters

475. Heaters

1. Question

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.
Note:
  1. 1.
    Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
  2. 2.
    Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
  3. 3.
    As long as a house is in the heaters' warm radius range, it can be warmed.
  4. 4.
    All the heaters follow your radius standard and the warm radius will the same.
Example 1:
1
Input: [1,2,3],[2]
2
3
Output: 1
4
5
Explanation:
6
The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
Copied!
Example 2:
1
Input: [1,2,3,4],[1,4]
2
3
Output: 1
4
5
Explanation:
6
The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the
Copied!

2. Implementation

(1) Binary Search
1
class Solution {
2
public int findRadius(int[] houses, int[] heaters) {
3
Arrays.sort(heaters);
4
int index = 0, res = 0;
5
6
for (int house : houses) {
7
index = binarySearch(heaters, house);
8
9
int distToLeftHeater = index >= 1 ? house - heaters[index - 1] : Integer.MAX_VALUE;
10
int distToRightHeater = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE;
11
12
res = Math.max(res, Math.min(distToLeftHeater, distToRightHeater));
13
}
14
return res;
15
}
16
17
public int binarySearch(int[] heaters, int target) {
18
int start = 0, end = heaters.length - 1, mid = 0;
19
20
while (start + 1 < end) {
21
mid = start + (end - start) / 2;
22
23
if (heaters[mid] < target) {
24
start = mid + 1;
25
}
26
else {
27
end = mid;
28
}
29
}
30
31
if (heaters[start] >= target) {
32
return start;
33
}
34
else if (heaters[end] >= target) {
35
return end;
36
}
37
else {
38
return heaters.length;
39
}
40
}
41
}
Copied!

3. Time & Space Complexity

Binary Search: 时间复杂度O(nlogn + mlogn), m为house的个数,n为heater的个数,空间复杂度O(logn),由于排序需要logn空间