leetcode 218. The Skyline Problem 优先级队列PriorityQueue + mulitset模拟Heap

A city’s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

这里写图片描述

这里写图片描述

Buildings Skyline Contour
The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .

The output is a list of “key points” (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], … ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.

For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].

Notes:

The number of buildings in any input list is guaranteed to be in the range [0, 10000].
The input list is already sorted in ascending order by the left x position Li.
The output list must be sorted by the x position.
There must be no consecutive horizontal lines of equal height in the output skyline. For instance, […[2 3], [4 5], [7 5], [11 5], [12 7]…] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: […[2 3], [4 5], [12 7], …]

这一道题比较长,问题就是给出所有建筑的轮廓图,就是计算各个拐点,没想出来怎么做,但是网上看了个答案,做法很棒,但是我自己应该想不出来。

这是一道十分棒的题,值得学习

这一道题涉及到使用优先队列,这个值得学习。

代码如下:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

/*
 * 这道题需要仔细考虑,不太容易想到
 * 
 * 一个简便的思路是,根据横坐标排序,然后遍历求拐点。
 * 求拐点的时候用一个最大化heap来保存当前的楼顶高度,
 * 遇到左边节点,就在heap中插入高度信息,遇到右边节点就 从heap中删除高度。
 * 分别用pre与cur来表示之前的高度与当前的高度,
 * 当cur != pre的时候说明出现了拐点。
 * */
public class Solution
{
    public List<int[]> getSkyline(int[][] buildings) 
    {
        List<int[]> res = new ArrayList<>();
        if(buildings==null || buildings.length<=0)
            return res;

        List<int[]> point=new ArrayList<>();
        for(int i=0;i<buildings.length;i++)
        {
            int[] one=buildings[i];
            point.add(new int[]{one[0],one[2]});
            point.add(new int[]{one[1],-one[2]});
        }

        Collections.sort(point, new Comparator<int []>() {
            @Override
            public int compare(int[] a, int[] b) {
                if(a[0]!=b[0])
                    return a[0]-b[0];
                else
                    return b[1]-a[1];
            }           
        });

        PriorityQueue<Integer> maxHeap=new PriorityQueue<>(Collections.reverseOrder());

        //cur记录当前的最高的高度,pre记录之前的高度。
        int cur=0,pre=0;
        for(int i=0;i<point.size();i++)
        {
            int[] one=point.get(i);
            if(one[1]>0)
            {
                maxHeap.add(one[1]);
                cur=maxHeap.peek();             
            }else 
            {
                maxHeap.remove(-one[1]);
                cur=maxHeap.peek()==null? 0 : maxHeap.peek();
            }

            if(pre!=cur)
            {
                res.add(new int[]{one[0],cur});
                pre=cur;
            }
        }
        return res;
    }
}

下面的是C++的做法,做法的思路和上面的一样,不一样的是优先级队列的使用,C++中有priority_queue就是一个队列,只支持头部元素的插入和删除,中间的不支持。所以这里使用的是multiset,因为他们是按照平衡二叉树设计的,所以begin()指向着最小值,rbegin()指向着最大值,所以就这么做了

代码如下:

#include <iostream>
#include <algorithm>
#include <vector>
#include <set>


using namespace std;


class Solution 
{
public:
    static bool cmp(pair<int, int> a, pair<int, int> b)
    {
        if (a.first != b.first)
            return a.first < b.first;
        else
            return a.second > b.second;
    }
    vector<pair<int, int>> getSkyline(vector<vector<int>>& build)
    {
        vector<pair<int, int>> res;
        if (build.size() <= 0)
            return res;
        vector<pair<int, int>> point;
        for (vector<int> i : build )
        {
            point.push_back(make_pair(i[0],i[2]));
            point.push_back(make_pair(i[1],-i[2]));
        }
        sort(point.begin(),point.end(),cmp);

        multiset<int> maxHeap;
        int cur = 0, pre = 0;
        for (pair<int, int> one : point)
        {
            if (one.second > 0)
            {
                maxHeap.insert(one.second);
                cur = *(maxHeap.rbegin());
            }
            else
            {
                maxHeap.erase(maxHeap.find(-one.second));
                cur = maxHeap.size()==0 ? 0 : *(maxHeap.rbegin());
            }
            if (cur != pre)
            {
                res.push_back(make_pair(one.first, cur));
                pre = cur;
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值