版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/86135294
Title:Hearter 475
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/heaters/
1. 基本的一次遍历
时间复杂度:O(n^2),嵌套循环。
空间复杂度:O(n),没有申请额外空间。
/**
* 如果只有一间房屋,需要找到:左侧最近的heater位于这个房屋的距离和右侧最近的heater位于这个房屋的距离,对每一个房屋进行左右侧进行查找
* @param houses
* @param heaters
* @return
*/
public static int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int i = 0;
int radius = 0;
for (int house : houses) {
while (i < heaters.length - 1 && house > heaters[i]) {
i++;
}
if (i != 0) {
radius = Math.max(radius, Math.min(house - heaters[i - 1], Math.abs(house - heaters[i])));
}
else {
radius = Math.max(Math.abs(house - heaters[0]), radius);
}
}
return radius;
}