Python | Leetcode Python题解之第218题天际线问题

题目:

题解:

python 复制代码
class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        buildings.sort(key=lambda bu:(bu[0],-bu[2],bu[1]))
        buildings.append([inf,inf,inf])
        heap = [[-inf,-inf,-inf]]
        ans = []
        for l,r,h in buildings:
            if heap[0][2] < l:
                topRight = heappop(heap)[2]
                while heap and topRight < l:
                    if heap[0][2] > topRight:
                        # 建筑群内有较较矮的建筑宽度比高的大,对齐进行切块
                        top = heappop(heap)
                        top[1], topRight = topRight, top[2]
                        # 如果新的切块也覆盖到新建筑,不需要再放入了
                        if topRight >= l: heappush(heap, top)
                        if ans[-1][1] != -top[0]: ans.append([top[1], -top[0]])
                    else: heappop(heap)
                if not heap: ans.append([topRight, 0])
            if not heap or h > -heap[0][0]: ans.append([l, h])
            if heap and heap[0][0] == -h and heap[0][2] < r: heap[0][2] = r
            else: heappush(heap, [-h,l,r])
        return ans[1:-1]
相关推荐
LiaoWL1237 分钟前
NumPy 入门实战(二):向量化与余弦相似度——从 ndarray 到 Embedding
python·numpy·embedding
forest_0927 分钟前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
databook4 小时前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析
文丑颜不良啊4 小时前
LeetCode2761~2780题目解析
java·leetcode
师夷长技以自愈4 小时前
手搓 AI Agent 第 8 篇:从手写循环到画流程图——LangGraph 封装
人工智能·python
aifannihao5 小时前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
用户019027581617 小时前
天勤 tqsdk 能做 A 股行情吗?期货强项与股票数据选型
python
文丑颜不良啊7 小时前
LeetCode2841~2860题目解析
java·leetcode
2601_967979128 小时前
pip在Python中的9个必须知道的用法
python·pip·版本控制·包管理工具·requirements.txt
曲径海盗9 小时前
【Python 学习第 58 天】列表方法
python·学习笔记·编程入门