代码改变世界

[LeetCode] 475. Heaters_Medium Tag: Sort, Two Pointers

2026-11-28 06:08  Johnson_强生仔仔  阅读(3)  评论(0)    收藏  举报

LeetCode 475 — Heaters | 原系统题单

Problem

Given house and heater positions on a line, find the smallest common heating radius that covers every house. A house is covered if at least one heater is within that radius.

houses = [1, 2, 3], heaters = [2] → 1
houses = [1, 2, 3, 4], heaters = [1, 4] → 1
houses = [1, 5], heaters = [2] → 3

思路:Sort + Two Pointers,两遍扫描

关键是先对每个 house 找最近 heater,再在所有 house 的最近距离中取最大值:answer = max(min_distance_for_each_house)。不能直接取扫描中遇到的最大距离,因为另一侧可能有更近的 heater。

分别排序 houses 与 heaters,不需要合并数组、类型标记或 dictionary。用 ans[i] 保存第 i 个 house 的最近距离。

  1. 从左往右,寻找右侧最近 heater。heater 在 house 左边时推进 heater 指针;第一个不小于 house 的 heater 就是右侧最近的,记录距离并推进 house 指针。
  2. 从右往左,寻找左侧最近 heater。heater 在 house 右边时向左推进 heater 指针;第一个不大于 house 的 heater 就是左侧最近的,和 ans[i] 取 min。
  3. 返回 max(ans)。每个 house 至少一侧能找到 heater。

例子

House右侧距离(heaters=[1,8])左侧距离最近距离
2 6 1 1
6 2 5 2
9 无穷大 1 1

houses=[2,6,9] 时答案是 max(1,2,1)=2。每户先取 min,全局再取 max。

Python:本次重写实现

class Solution:
    def findRadius(self, houses: list[int], heaters: list[int]) -> int:
        houses.sort()
        heaters.sort()
        m, n = len(houses), len(heaters)
        maxVal = max(houses[-1], heaters[-1]) + 1
        ans = [maxVal] * m

        # Right side closest heater
        house_idx, heater_idx = 0, 0
        while house_idx < m and heater_idx < n:
            if houses[house_idx] <= heaters[heater_idx]:
                ans[house_idx] = heaters[heater_idx] - houses[house_idx]
                house_idx += 1
            else:
                heater_idx += 1

        # Left side closest heater
        house_idx, heater_idx = m - 1, n - 1
        while house_idx >= 0 and heater_idx >= 0:
            if houses[house_idx] >= heaters[heater_idx]:
                ans[house_idx] = min(
                    ans[house_idx], houses[house_idx] - heaters[heater_idx]
                )
                house_idx -= 1
            else:
                heater_idx -= 1
        return max(ans)

Time Complexity

设 m=len(houses),n=len(heaters)。两次排序共 O(m log m + n log n);两遍扫描共 O(m+n),因为每个指针只单向移动,不会为每个 house 从头扫描 heaters。最终 max(ans) 为 O(m)。整体是 O(m log m + n log n),等价于 O(max(m log m,n log n))(长度为1时排序为常数,完整表达也可加上m+n)。

Space Complexity

ans 数组使用 O(m)。Python list.sort() 虽然原地修改列表,仍可能使用线性临时空间;两次排序先后执行,峰值额外空间为 O(m+n),等价于 O(max(m,n))。仅计算扫描与结果数组时是 O(m)。不能把原地排序直接等同于 O(1) 辅助空间。

边界与易错点

  • house 与 heater 重合时距离为0。
  • 所有 heater 都在一侧时,另一遍扫描负责填入有效距离。
  • 支持重复坐标与未排序输入。
  • 题目两数组非空,可安全读取 [-1]。
  • maxVal=max(houses[-1],heaters[-1])+1 是大于任意真实距离的哨兵,因为题目坐标均为正数。若允许负坐标,应改用 float('inf') 等可靠上界。
  • 首次分析仅计算扫描 O(m+n) 与 ans O(m),补计 Python 排序后得到上述整体复杂度。

Interview explanation

“I sort both arrays, then scan in both directions to find the closest heater on each side of every house. I keep the smaller distance for each house and return the largest of those distances. Sorting dominates the running time.”

学习来源:根据双向扫描的 C++ 解法截图理解后,用 Python 重写;本轮只进行了代码及基本边界走查,未声称提交已 Accepted。

本文基于本人练习代码,由 AI 辅助整理讲解。