这道题没做出来,记录一下
红黑树,问题在与比较器一直没做出来,左神的方法有问题啊,(1,2,2),(1,2,3),(1,2,4)那种方法左神是没法处理的,我就在比较器上下工夫,发现还是不行
这道题用的红黑树,我本来想用数组和哈希,结果发现这道题需要时时获取数据的最大值,而且弹出一个元素后还得能获取最大值,还要支持下标获取,堆也凉了。
先对数组sort一下,获取的时候每次的操作,是上升还是下降,排序后就按照n的顺序来。用heightTimes来获取时时的高度,也方便找最大高度。pos2height用于获取每个n的最大高度。
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
#define UP 0
#define DOWN 1
class operation
{
public:
int n;///<水平坐标
int height;
int direction;
operation(int _n, int _height, int _direction):n(_n),height(_height),direction(_direction){};
};
static bool cmp(operation a1, operation a2)
{
if(a1.n<a2.n)
return true;
else if(a1.n>a2.n)
return false;
else if(a1.direction==UP && a2.direction==DOWN)
return true;
else if(a2.direction==DOWN && a1.direction==UP)
return false;
else if(a1.direction==UP && a2.direction==UP)
return a1.height<a2.height;
else if(a1.direction==DOWN && a2.direction==DOWN)
return a1.height>a2.height;
return true;
}
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
vector<operation>vec_operation;
for(auto vecOp:buildings)
{
vec_operation.push_back(operation(vecOp[0], vecOp[2], UP));
vec_operation.push_back(operation(vecOp[1], vecOp[2], DOWN));
}
sort(vec_operation.begin(), vec_operation.end(), cmp);
vector<vector<int> >ret;
map<int, int>heightTimes;///<哪个高度出现的次数
map<int, int>pos2height;///<哪个位置的高度,这个红黑树是要有的,同一个位置可能有多个高度
for(auto vecOp:vec_operation)
{
if(UP==vecOp.direction)
{
auto it=heightTimes.find(vecOp.height);
if(it!=heightTimes.end())
++it->second;
else
heightTimes[vecOp.height] = 1;
}
else
{
auto it=heightTimes.find(vecOp.height);///<因为比较器,down一定出现在up之后,即这里一定能找到
if(it->second-1==0)
heightTimes.erase(vecOp.height);
else
--it->second;
}
if(!heightTimes.empty())
{
auto it = heightTimes.end();
--it;
if(UP==vecOp.direction)
pos2height[vecOp.n] = max(vecOp.height, it->first);
else
pos2height[vecOp.n] = min(vecOp.height, it->first);
}
else
pos2height[vecOp.n] = 0;
}
int heightLast=0;
for(auto pairheight:pos2height)
{
int heightCur = pairheight.second;
if(heightLast!=heightCur)
ret.push_back({pairheight.first, pairheight.second});
heightLast = heightCur;
}
return ret;
}
int main(void)
{
// vector<vector<int> >a={{1,2,1},{1,2,2},{1,2,3}};
vector<vector<int> >a={{2,9,10},{3,7,15},{5,12,12},{15,20,10},{19,24,8}};
getSkyline(a);
return 0;
}