解法一:双数组循环
思路:求出每个房子与离他最近的供暖器的距离,然后在这些距离中求出最大的(最大就可以保证全覆盖),第一次使用双重循环:就是先遍历房子的数组,再遍历暖器的数组,然后就超时了;第二次,首先对两个数组排序,然后在求距离时就可以根据相邻两个值的大小确定是不是最小值。
public static void main(String[] args) {
int[] houses = {1,2,3};
int[] heaters = {2};
System.out.println(findRadius(houses, heaters));
}
public static int findRadius(int[] houses, int[] heaters) {
//对两个数组排序
Arrays.sort(heaters);
Arrays.sort(houses);
//r代表最后要返回的最大值
//m代表每个房子与供暖器最短的距离
int r = Integer.MIN_VALUE;
int m = Integer.MAX_VALUE;
int j = 0;
//遍历所有房子
for(int i = 0;i < houses.length;i++){
//j保证在暖器数组内运算,如果前一个值比下一个值要大,就要继续遍历。否则就返回Math.max(r, Math.abs(heaters[j] - houses[i]));
while(j < heaters.length - 1 && Math.abs(heaters[j] - houses[i]) >= Math.abs(heaters[j + 1] - houses[i]))
j++;
r = Math.max(r, Math.abs(heaters[j] - houses[i]));
}
return r;
}
解法二:
双指针:
class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int l_house = houses.length;
int l_heat = heaters.length;
//供暖最小编号 > 房屋最大编号
if (heaters[0] >= houses[l_house - 1]) {
return heaters[0] - houses[0];
}
//供暖最大编号 < 房屋最先编号
if (heaters[l_heat - 1] <= houses[0]) {
return houses[l_house - 1] - heaters[l_heat - 1];
}int radius = 0;
int i=0, j=0;
//最小房屋 < 最小供暖,初始化radius值
if (houses[0] < heaters[0]) {
radius = heaters[0] - houses[0];
}
//i后移到第一个供暖,初试化i,保障之后比较时前后都有供暖,比较前后供暖距离
while (houses[i] <= heaters[j]) {
i++;
}
while (i < l_house && j < l_heat - 1) {
//如果当前房屋 < 下一个供暖,比较到前后供暖的距离
if (houses[i] <= heaters[j+1]) {
radius = Math.max(radius, Math.min(houses[i]-heaters[j], heaters[j+1]-houses[i]));
i++; //房屋下标后移
}else{ //否则供暖下标后移
j++;
}
}
//如果已经到了最后一个供暖,还有房屋未遍历,最小距离就是 最大房屋编号 - 最后大供暖编号
if (i < l_house) {
radius = Math.max(radius, houses[l_house-1] - heaters[l_heat-1]);
}return radius;
}
}
对Math.abs(heaters[i] - house) >= Math.abs(heaters[i + 1] - house) 的解读:
houses:1,2,3,4
heaters:1,4
对于 house 1,heater 1 比 heater 4 更接近 house1,所以不将 i 移动到 i + 1
对于 house 2,heater 1 比 heater 4 更接近 house2,所以不将 i 移动到 i + 1
对于 house 3,heater 4 比 heater 1 更接近 house3,所以将 i 移动到 i + 1
对于 house 4,依次类推
class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);int res = 0;
int i = 0;
for (int house : houses) {
while (i < heaters.length - 1 &&
Math.abs(heaters[i] - house) >= Math.abs(heaters[i + 1] - house)) {
i++;
}
res = Math.max(res, Math.abs(heaters[i] - house));
}return res;
}
}