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]
相关推荐
什巳1 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_796826521 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
吴梓穆2 小时前
Python 基础 正则表达式
python
巧克力男孩dd3 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
闲猫3 小时前
LangChain / Core components / Models
开发语言·python·langchain
cui_ruicheng6 小时前
Python从入门到实战(十三):模块、包与环境管理
开发语言·python
CoderYanger6 小时前
A.每日一题:3020. 子集中元素的最大数量
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
李宸净6 小时前
Web自动化测试selenium+python
前端·python·selenium
而后笑面对7 小时前
生信bwa算法
python
什巳7 小时前
JAVA练习312- 二叉搜索树中第 K 小的元素
java·数据结构·算法·leetcode