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]
相关推荐
godspeed_lucip3 分钟前
LLM和Agent——专题6:Multi Agent 入门(5)
人工智能·python
小欣加油22 分钟前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
Metaphor6921 小时前
使用 Python 给 PDF 设置背景色或背景图
数据库·python·pdf
郝亚军1 小时前
如何让pycharm-2026.1.2顶部菜单栏固定显示在最上端
python
怪兽学LLM2 小时前
LeetCode 438 找到字符串中所有字母异位词(Python 固定滑动窗口+字符计数解法)
python·算法·leetcode
麻雀飞吧2 小时前
期货量化日志别泄露密码:天勤账户凭证脱敏写法
python
CC数学建模2 小时前
2026年江西省研究生数学建模竞赛1题:空间数据分析中的过拟合识别完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
matlabgoodboy2 小时前
计算机java程序代写python代码编写c/c++代做qt设计php开发matlab
java·c语言·python
不考研当牛马2 小时前
Django 框架 深度学习
python·深度学习·django