leetcode 218. 天际线问题

题意:

在这里插入图片描述
在这里插入图片描述
如第一幅图所示,求由很多可能重叠矩形能够覆盖最终的最终图案的形状,如第二幅图所示。

思路:

  • 用扫描线思想, 从左往右扫描,另外加上一个最大堆来维护满足条件的所有矩形里的高度的最高值。

  • 另外实现的时候有一些小细节很巧妙。

  • c++和python里对元组的排序,默认都是从低位从小大大排序。

  • 时间复杂度: (nlogn)

代码:

class Solution:
    def getSkyline(self, buildings) :
        res = [0,0]
        builds = []
        for l, h, r in builds:
            builds.append(l , -h, r)
            builds.append(r, h, 0)
        builds.sort()
        import heapq
        heap = [[0, float('inf')]]
        for l, h ,r in builds:
            while l >= heap[0][1]:
                heapq.heappop(heap)
            if h<0:
                heapq.heappush(heap, [h ,r])
            if res[-1][1] != heap[0][0]:
                res.append(l , -heap[0][0])
        return res
class Solution {
public:
    vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
          vector<vector<int>> builds;
          vector<vector<int>> res;
          for(auto& build : buildings){
              builds.push_back({build[0], -build[2]});
              builds.push_back({build[1], build[2]});
          }
          sort(builds.begin(), builds.end());
          multiset<int> big_heap({0});
          vector<int> last = {0,0};
          for(auto& item: builds){
             if(item[1]<0) big_heap.insert(-item[1]);
             else  big_heap.erase(big_heap.find(item[1]));

             auto max_height = *big_heap.rbegin();
             if(last[1]!= max_height){
                last[0] = item[0];
                last[1] = max_height;
                res.push_back(last);
             }
          }
          return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值