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]
相关推荐
jack1868913 分钟前
Github Copilot 高效开发实战场景指南
python
AIFQuant13 分钟前
Python A股实时行情API接入:沪深股票数据与WebSocket推送实战
开发语言·python·websocket·金融·a股行情
小小龙学IT14 分钟前
Python Matplotlib 数据可视化库深度解析
python·信息可视化·matplotlib
小小张说故事27 分钟前
Python 到底是值传递还是引用传递?一个赋值实验讲透,别再背结论了
python
Maxwin28 分钟前
AI 生成的视频怎么局部修改?2026 年分章生成 Manim 代码的最新做法
python·aigc
第六种自由39 分钟前
[路飞]_Leetcode 22. 括号生成
javascript·算法·leetcode
Java后端的Ai之路1 小时前
07React_Props验证器
人工智能·python·react.js·架构·fastapi
Eider19981 小时前
为Loop Engineering装刹车
python·vibe coding·agent设计模式·loopengineering
kaixin_啊啊1 小时前
【零基础学AI】第 9 章——安装 Python 和开发工具
人工智能·python
longlongzihan1 小时前
LeetCode 24.两两交换链表中的节点:虚拟头结点与指针
算法·leetcode·链表