LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub

218. 天际线问题

城市的天际线是从远处观看该城市中所有建筑物形成的轮廓的外部轮廓。给你所有建筑物的位置和高度,请返回由这些建筑物形成的 天际线

每个建筑物的几何信息由数组 buildings 表示,其中三元组 buildings[i] = [lefti, righti, heighti] 表示:

天际线 应该表示为由 “关键点” 组成的列表,格式 [[x1,y1],[x2,y2],...] ,并按 x 坐标 进行 排序关键点是水平线段的左端点。列表中最后一个点是最右侧建筑物的终点,y 坐标始终为 0 ,仅用于标记天际线的终点。此外,任何两个相邻建筑物之间的地面都应被视为天际线轮廓的一部分。

注意:输出天际线中不得有连续的相同高度的水平线。例如 [...[2 3], [4 5], [7 5], [11 5], [12 7]...] 是不正确的答案;三条高度为 5 的线应该在最终输出中合并为一个:[...[2 3], [4 5], [12 7], ...]

示例 1:

img

输入:buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
输出:[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
解释:
图 A 显示输入的所有建筑物的位置和高度,
图 B 显示由这些建筑物形成的天际线。图 B 中的红点表示输出列表中的关键点。

示例 2:

输入:buildings = [[0,2,3],[2,5,3]]
输出:[[0,3],[5,0]]

提示:

扫描线 困难

代码

from sortedcontainers import SortedList
class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        ans = []

        # 预处理所有的点,为了方便排序,对于左端点,令高度为负;对于右端点令高度为正
        ps = []
        for l, r, h in buildings:
            ps.append((l, - h))
            ps.append((r, h))
        # 先按照横坐标进行排序
        # 如果横坐标相同,则按照左端点排序
        # 如果相同的左/右端点,则按照高度进行排序
        ps.sort()

        prev = 0
        # 有序列表充当大根堆
        q = SortedList([prev])

        for point, height in ps:
            if height < 0:
                # 如果是左端点,说明存在一条往右延伸的可记录的边,将高度存入优先队列
                q.add(-height)
            else:
                # 如果是右端点,说明这条边结束了,将当前高度从队列中移除
                q.remove(height)
            
            # 取出最高高度,如果当前不与前一矩形“上边”延展而来的那些边重合,则可以被记录
            cur = q[-1]
            if cur != prev:
                ans.append([point, cur])
                prev = cur

        return ans

还有一个比较快的版本

class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        events = [(l, -h, r) for l, r, h in buildings]
        events += [(r, 0, 0) for _, r, _ in buildings]
        events.sort()
        
        res = [[0, 0]]
        queue = [(0, float('inf'))]
        for l, minusH, r in events:
            h = -minusH
            while l>=queue[0][1]:
                heapq.heappop(queue)
            if h:
                heapq.heappush(queue, (-h, r))
            if res[-1][1] != -queue[0][0]:
                res.append([l, -queue[0][0]])
        return res[1:]