475. 供暖器
冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
在加热器的加热半径范围内的每个房屋都可以获得供暖。
现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置,请你找出并返回可以覆盖所有房屋的最小加热半径。
说明:所有供暖器都遵循你的半径标准,加热的半径也一样。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/heaters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二分
import java.util.Arrays;
class Solution {
private int search(int[] heaters, int target) {
int l = 0, r = heaters.length - 1;
while (l <= r) {
int mid = (l + r) >> 1;
if (heaters[mid] < target) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return l;
}
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(heaters);
int ans = 0;
for (int house : houses) {
int index = search(heaters, house);
int distance = index == 0 ? heaters[index] - house :
(index == heaters.length ? house - heaters[index - 1] :
Math.min(house - heaters[index - 1], heaters[index] - house));
ans = Math.max(ans, distance);
}
return ans;
}
}
双指针
import java.util.Arrays;
class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int ans = 0;
int index1 = 0, index2 = 0;
while (index1 < houses.length && index2 < heaters.length) {
int distance = Math.abs(houses[index1] - heaters[index2]);
while (index2 < heaters.length - 1 && Math.abs(houses[index1] - heaters[index2 + 1]) <= distance) {
distance = Math.abs(houses[index1] - heaters[++index2]);
}
ans = Math.max(ans, distance);
index1++;
}
return ans;
}
}
心之所向,素履以往 生如逆旅,一苇以航
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~