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]
相关推荐
alwaysrun3 分钟前
Python之文档自动上传至飞书云盘
python·飞书·uploader·云盘
如何原谅奋力过但无声5 分钟前
【灵神高频面试题合集04-05】二分查找
数据结构·python·算法·leetcode
财经资讯数据_灵砚智能6 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年5月3日
大数据·人工智能·python·信息可视化·自然语言处理
西红柿炒番茄3110 分钟前
【Python】一个自动切换壁纸的python程序
开发语言·python
跨境数据猎手12 分钟前
B 站 item_search_video 接口开发,搭建生产级视频搜索服务
大数据·爬虫·python
EnCi Zheng17 分钟前
03ab-PyTorch安装教程 [特殊字符]
人工智能·pytorch·python
SmartBrain22 分钟前
从Prompt工程到Harness工程:AI Agent落地之路
人工智能·python·华为·aigc
X56618 小时前
如何在 Laravel 中正确保存嵌套动态表单数据(主服务与子服务)
jvm·数据库·python
ZhengEnCi9 小时前
03ab-PyTorch安装教程 📚
python
穿条秋裤到处跑9 小时前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展