手机版 欢迎访问it开发者社区(www.mfbz.cn)网站

当前位置: > 开发

leetcode专题训练 218. The Skyline Problem

时间:2021/4/27 15:34:49|来源:|点击: 次

最开始看到这道题先想的线段树,后来发现并不用得上线段树。看题解直接把所有的线扫一遍就行了。参考题解写了一份代码,估计下回遇到这道题还是不会做哈哈哈哈哈。

import queue

class Node:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __lt__(self, other):
        if self.x == other.x:
            return self.y < other.y
        return self.x < other.x

class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        l = len(buildings)
        if l == 0:
            return []
        
        result = []
        points = queue.PriorityQueue()

        # 遍历处理buildings,标识是出还是入 O(n)
        for i in range(l):
            # y负值时是进入矩形,正值时是退出矩形
            points.put(Node(buildings[i][0], -buildings[i][2]))
            points.put(Node(buildings[i][1], buildings[i][2]))

        # print(points)
        heights = []
        last = 0
        while not points.empty():
            now = points.get()
            if now.y < 0:
            	# 添加一个高度
                heights.append(-now.y)
            else:
            	# 删除一个高度
                heights.remove(now.y)
                
            # 按照高度逆序排列
            heights.sort(reverse=True)

            # 如果当前heights为空,或者和之前的最高值不同了,说明在now.x时到了关键节点
            if not heights:
                result.append([now.x, 0])
            elif heights[0] != last:
                result.append([now.x, heights[0]])
                last = heights[0]
        
        return result

附:
c++和python的数据结构对应。(转载自https://cloud.tencent.com/developer/ask/43952的某个用户回答)

DataStructure = {'Collections': {'Map': [('dict', 'OrderDict', 'defaultdict'),
                                         ('chainmap', 'types.MappingProxyType')],
                                 'Set': [('set', 'frozenset'), {'multiset':'collection.Counter'}]},
                                 'Sequence': {'Basic': ['list', 'tuple', 'iterator']},
                                              'Algorithm': {'Priority': ['heapq',
                                                                         'queue.PriorityQueue'],
                                                            'Queue': ['queue.Queue',
                                                                      'multiprocessing.Queue'],
                                                            'Stack': ['collection.deque',
                                                                      'queue.LifeQueue']},
                 'text_sequence': ['str', 'byte', 'bytearray']}

Copyright © 2002-2019 某某自媒体运营 版权所有