forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heaters.java
33 lines (30 loc) · 1.2 KB
/
Heaters.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.Arrays;
public class Heaters {
private static int binarySearch(int[] array, int element) {
int left = 0, right = array.length - 1, middle;
while (left <= right) {
middle = (left + right) / 2;
if (array[middle] == element) return middle;
else if (array[middle] < element) left = middle + 1;
else right = middle - 1;
}
return left;
}
public static void main(String[] args) {
System.out.println(findRadius(new int[] {1, 2, 3, 4}, new int[] {1, 4}));
}
public static int findRadius(int[] houses, int[] heaters) {
Arrays.sort(heaters);
int minRadius = 0, leftRadius, rightRadius;
for (int house : houses) {
int index = binarySearch(heaters, house);
if (index < heaters.length && house == heaters[index]) {
continue;
}
leftRadius = index > 0 ? house - heaters[index - 1] : Integer.MAX_VALUE;
rightRadius = (index == heaters.length ? Integer.MAX_VALUE : heaters[index] - house);
minRadius = Math.max(minRadius, Math.min(leftRadius, rightRadius));
}
return minRadius;
}
}