难度:medium
可以采用双指针分别遍历houses和heaters,哥么的注释很详细;
Java:
排序+双指针:
class Solution {
public int findRadius(int[] houses, int[] heaters) {
//排序
Arrays.sort(houses);
Arrays.sort(heaters);
//加热半径
int radius = 0;
//house[i]距离左右最近的两个heater的距离的最小值:即使house[i]受热的最小加热半径
int leftDistance = 0;
int rightDistance = 0;
//求覆盖所有房屋的最小加热半径,即所有house的最小加热半径 的最大值
//i遍历houses
for (int i = 0; i < houses.length; i++) {
//j遍历heaters
for (int j = 0; j < heaters.length; j++) {
if (houses[i] <= heaters[j]) {
//处理数组越界的情况
if (j == 0) {
leftDistance = Integer.MAX_VALUE;
} else {
leftDistance = houses[i] - heaters[j - 1];
}
rightDistance = heaters[j] - houses[i];
} else {
//处理数组越界的情况
if (j == heaters.length - 1) {
rightDistance = Integer.MAX_VALUE;
} else {
rightDistance = heaters[j] - houses[i];
}
leftDistance = houses[i] - heaters[j];
}
radius = Math.max(radius, Math.min(leftDistance, rightDistance));
}
}
return radius;
}
}
复杂度分析:
- 时间复杂度:O(mlogm+nlogn),两个数组排序所用需的时间
- 空间复杂度:O(logm+logn),两个数组排序所用需的空间
还可以使用排序+二分查找的方法!!