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;
}
};
leetcode:the skyline problem
最新推荐文章于 2024-08-30 11:06:53 发布