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]
相关推荐
凌肖战7 分钟前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
黑听人19 分钟前
【力扣 简单 C】70. 爬楼梯
c语言·leetcode
Tipriest_1 小时前
Python关键字梳理
python·关键字·keyword
ゞ 正在缓冲99%…1 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
Kaltistss2 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展
im_AMBER2 小时前
学习日志05 python
python·学习
大虫小呓2 小时前
Python 处理 Excel 数据 pandas 和 openpyxl 哪家强?
python·pandas
哪 吒3 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
摸爬滚打李上进4 小时前
重生学AI第十六集:线性层nn.Linear
人工智能·pytorch·python·神经网络·机器学习
凛铄linshuo5 小时前
爬虫简单实操2——以贴吧为例爬取“某吧”前10页的网页代码
爬虫·python·学习