leetcode:the skyline problem

class Solution
{
public:
    struct node
    {
        int x, heightIndex;
        bool leftOrRight;
        node(int _x, int _heightIndex, bool _leftOrRight):x(_x), heightIndex(_heightIndex), leftOrRight(_leftOrRight) {}
    };
    static bool cmp(const node & a, const node & b)//去掉static報錯
    {
        if(a.x != b.x)
            return a.x < b.x;//小於號不能換成減號
        return a.leftOrRight < b.leftOrRight;
    }
    vector<pair<int, int> > getSkyline(vector<vector<int> >& buildings)
    {
        vector<pair<int, int> > res;
        vector<node> edge;
        vector<int> height;
        int i, index;
        for(i = 0; i < buildings.size(); i++)
        {
            index = height.size();
            edge.push_back(node(buildings[i][0], index, false));
            edge.push_back(node(buildings[i][1], index, true));
            height.push_back(buildings[i][2]);
        }
        sort(edge.begin(), edge.end(), cmp);
        multiset<int> active;
        int currentHeight = 0, newHeight, newX;
        for(i = 0; i < edge.size(); i++)
        {
            if(edge[i].leftOrRight == false)
            {
                active.insert(edge[i].heightIndex);
                newHeight = height[edge[i].heightIndex];
                newX = edge[i].x;
                while(i + 1 < edge.size() && edge[i].x == edge[i + 1].x && edge[i + 1].leftOrRight == false)
                {
                    active.insert(edge[i + 1].heightIndex);
                    newHeight = max(newHeight, height[edge[i + 1].heightIndex]);
                    i++;
                }
                if(currentHeight < newHeight)
                {
                    res.push_back(make_pair(newX, newHeight));
                    currentHeight = newHeight;
                }
            }
            else
            {
                active.erase(edge[i].heightIndex);
                newHeight = height[edge[i].heightIndex];
                newX = edge[i].x;
                while(i + 1 < edge.size() && edge[i].x == edge[i + 1].x && edge[i + 1].leftOrRight == true)
                {
                    active.erase(edge[i + 1].heightIndex);
                    newHeight = max(newHeight, height[edge[i + 1].heightIndex]);
                    i++;
                }
                if(currentHeight == newHeight)
                {
                    multiset<int> :: iterator it;
                    int maxHeight = 0;
                    for(it = active.begin(); it != active.end(); it++)
                        maxHeight = max(maxHeight, height[*it]);
                    if(newHeight > maxHeight)
                    {
                        res.push_back(make_pair(newX, maxHeight));
                        currentHeight = maxHeight;
                    }
                }
            }
        }
        return res;
    }
};

發佈了101 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章