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]
相关推荐
hef28834 分钟前
SQL和Python怎么选?数据分析工具实战指南
python·sql·数据分析
徐安安ye35 分钟前
FlashAttention长程依赖建模:局部+全局的Hybrid Spiral结构设计
python·深度学习·机器学习
IT策士1 小时前
Django 从 0 到 1 打造完整电商平台:商品排序与浏览量统计
后端·python·django
godspeed_lucip1 小时前
LLM和Agent——专题3: Agentic Workflow 入门(4)
人工智能·python
godspeed_lucip1 小时前
LLM和Agent——专题3: Agentic Workflow 入门(2)
网络·人工智能·python
mingshili1 小时前
[Python] Python中自带模块级的单例模式-不需要定义单例类
python·单例模式
alphaTao1 小时前
LeetCode 每日一题 2026/5/18-2026/5/24
python·leetcode
徐安安_ye11 小时前
FlashAttention学习路线:从调API到写算子,你该走哪条路
python·学习
IT策士2 小时前
Django 从 0 到 1 打造完整电商平台:商品搜索
后端·python·django
茉莉玫瑰花茶2 小时前
LangGraph 持久化(Persistence)[ 2 ]
开发语言·python·ai·langgraph