# LeetCode算法题-Heaters（Java实现）

### 01 看题和准备

• 您给出的房屋和加热器的数量是非负数，不会超过25000。

• 您给出的房屋和加热器的位置是非负的，不会超过10 ^ 9。

• 只要房子在加热器的温暖半径范围内，就可以加热。

• 所有加热器都遵循半径标准，温暖半径也是如此。

### 02 第一种解法

public int findRadius(int[] houses, int[] heaters) {
if (houses == null || heaters == null) {
return 0;
}
int result = Integer.MIN_VALUE;
Arrays.sort(houses);
Arrays.sort(heaters);
int i = 0, j = 0;
while (i < houses.length) {
while (j < heaters.length-1 && Math.abs(heaters[j+1] - houses[i]) <=
Math.abs(heaters[j] - houses[i])) {
j++;
}
result = Math.max(result, Math.abs(heaters[j] - houses[i]));
i++;
}
return result;
}

### 03 第二种解法

public int findRadius2(int[] houses, int[] heaters) {
if (houses == null || heaters == null) {
return 0;
}
Arrays.sort(heaters);
int result = Integer.MIN_VALUE;
for (int i=0; i<houses.length; i++) {
}
return result;
}

public int findOne(int house, int[] heaters) {
int start = 0, end = heaters.length-1;
int left = Integer.MAX_VALUE, right = Integer.MAX_VALUE;
while (start <= end) {
int mid = (start+end)/2;
int heater = heaters[mid];
if (house == heater) {
return 0;
} else if (house < heater) {
right = heater - house;
end = mid - 1;
} else {
left = house - heater;
start = mid + 1;
}
}
return Math.min(left, right);
}

### 04 第三种解法

public int findRadius3(int[] houses, int[] heaters) {
if (houses == null || heaters == null) {
return 0;
}
Arrays.sort(heaters);
int result = Integer.MIN_VALUE;
for (int house : houses) {
int index = Arrays.binarySearch(heaters, house);
if (index < 0) {
index = -(index + 1);
}
int dis = index-1 >= 0 ? house - heaters[index-1] : Integer.MAX_VALUE;
int dis2 = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE;
result = Math.max(result, Math.min(dis, dis2));
}
return result;
}

### 05 小结

posted @ 2019-01-23 09:15 小川94 阅读(...) 评论(...) 编辑 收藏