# Leetcode 475. Heaters

class Solution { // 1014 ms
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(heaters);

int[] lefts = new int[houses.length];
int[] rights = new int[houses.length];
for (int i = 0; i < houses.length; i++) {
int left = 0, right = heaters.length - 1;
while (left < heaters.length && heaters[left] <= houses[i]) {
lefts[i] = left + 1;
left++;
}
while (right >= 0 && heaters[right] >= houses[i]) {
rights[i] = right + 1;
right--;
}

}

int ret = 0;
for (int i = 0; i < houses.length; i++) {
int min = Integer.MAX_VALUE;
if (lefts[i] != 0) {
min = Math.min(houses[i] - heaters[lefts[i] - 1], min);
}
if (rights[i] != 0) {
min = Math.min(heaters[rights[i] - 1] - houses[i], min);
}
ret = Math.max(min, ret);
}

return ret;
}
}

class Solution { // 699ms
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(heaters);
int res = 0;

for (int i = 0; i < houses.length; i++) {
int left = 0, right = 0;
int start = 0, end = heaters.length - 1;
while (start < heaters.length && heaters[start] <= houses[i]) {
left = start + 1;
start++;
}
start = left != 0 ? (left - 1) : 0;
while(end >= start && heaters[end] >= houses[i]) {
right = end + 1;
end--;
}

int min = Integer.MAX_VALUE;
if (left != 0) {
min = Math.min(min, houses[i] - heaters[left - 1]);
}
if (right != 0) {
min = Math.min(min, heaters[right - 1] - houses[i]);
}
res = Math.max(res, min);
}

return res;
}
}

class Solution { // 26 ms
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(heaters);
int res = 0;
for (int i = 0; i < houses.length; i++) {
int index = Arrays.binarySearch(heaters, houses[i]);
if (index < 0) {
index = ~index;
int left = index - 1 >= 0 ? houses[i] - heaters[index - 1] : Integer.MAX_VALUE;
int right = index < heaters.length ? heaters[index] - houses[i] : Integer.MAX_VALUE;
res = Math.max(Math.min(left, right), res);
}
}
return res;
}
}

• 评论

• 上一篇
• 下一篇