The Skyline Problem
KS Summer Academy

The Skyline Problem

Description

link

Given a list of buildings/retangles based on the y=0. Each building is represented by [L, R, H], L,R is the x-coordinate, and H is the height. Return a list of key points, the left endpoint of a horizontal line segment.

Thoughts

Detailed setting

To traverse buildings from left to right, x from 0 to LLong_Max.

To maintain L and the que -

Code

Assuming N buildings.

Time complexity: O(NlogN)

Space complexity: O(N)

bool cmp(const vector<int>& a, const vector<int>& b){
    if(a[0] == b[0]){
        if(a[2] == b[2]) return a[1] < b[1];
        return a[2] > b[2];
    }
    return a[0] < b[0];
}
class Solution {
public:
    vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
        vector<vector<int>> keyPoints;
        if(buildings.size() == 0) return keyPoints;
        sort(buildings.begin(), buildings.end(), cmp);
        int idx = 0, N = buildings.size(), height = 0;
        long long L = buildings[0][0];
        priority_queue< pair<int,long long> > que;
        que.push( make_pair(0, LLONG_MAX) );
        while( L < LLONG_MAX ){
            clean( que, L );
            if( que.top().first > height ){
                keyPoints.push_back( {L, que.top().first } );
                height = que.top().first;
            }
            if( idx < N && buildings[idx][0] <= que.top().second ){
                L = buildings[idx][0];
                if( buildings[idx][0] == que.top().second && buildings[idx][2] != que.top().first) height = -1;
                que.push( make_pair(buildings[idx][2], buildings[idx][1]) );
                idx += 1;
            }else{
                L = que.top().second;
                height = -1;
                que.pop();
            }
        }
        return keyPoints;
    }
private:
    void clean(priority_queue< pair<int,long long> >& que, int L){
        while(que.top().second <= L) que.pop();
    }
};
*****
Written by Mi on 06 August 2019