Given N buildings in a x-axis,each building is a rectangle and can be represented by a triple (start, end, height),where start is the start position on x-axis, end is the end position on x-axis and height is the height of the building. Buildings may overlap if you see them from far away,find the outline of them。
An outline can be represented by a triple, (start, end, height), where start is the start position on x-axis of the outline, end is the end position on x-axis and height is the height of the outline.
Notice
Please merge the adjacent outlines if they have the same height and make sure different outlines cant overlap on x-axis.
Given 3 buildings:
[
[1, 3, 3],
[2, 4, 4],
[5, 6, 1]
]
The outlines are:
[
[1, 2, 3],
[2, 4, 4],
[5, 6, 1]
]
思路是这样的:用一个hashtable 保持住在x位置还“存活”的矩阵的高度, 如果当前的高度不一致,说明前面一个矩阵可以闭合了,并且新开一个矩阵。
class Solution {
public:
/**
* @param buildings: A list of lists of integers
* @return: Find the outline of those buildings
*/
vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) {
// write your code here
vector<vector<int>> res;
vector<int> p;
multiset<int, greater<int>> mulset;
mulset.insert(-1);
unordered_map<int, int> map_section_alive;
unordered_map<int,vector<int>> map_start;
unordered_map<int,vector<int>> map_end;
int section = 0;
for (int i = 0; i < buildings.size(); i++) {
int s = buildings[i][0];
int e = buildings[i][1];
int h = buildings[i][2];
if (map_start.find(s) == map_start.end()) {
vector<int> vec;
map_start[s] = vec;
}
if (map_end.find(e) == map_end.end()) {
vector<int> vec;
map_end[e] = vec;
}
map_start[s].push_back(h);
map_end[e].push_back(h);
p.push_back(s);
p.push_back(e);
}
sort(p.begin(), p.end());
p.erase(unique(p.begin(), p.end()), p.end());
// for (int i = 0; i <p.size(); i++) {
// cout<<p[i]<<" ";
// }
vector<int> temp = {-1,-1,-1};
for (int i = 0; i < p.size(); i++) {
if (map_start.find(p[i]) != map_start.end()) {
for (int j = 0; j < map_start[p[i]].size(); j++) {
int height = map_start[p[i]][j];
if (map_section_alive.find( height ) == map_section_alive.end()) {
map_section_alive [ height ] = 0;
}
map_section_alive [ map_start[p[i]][j] ]++;
if (map_section_alive [ height ] == 1) {
mulset.insert(height);
}
}
}
if (map_end.find(p[i]) != map_end.end()) {
for (int j = 0; j < map_end[p[i]].size(); j++) {
int height = map_end[p[i]][j];
map_section_alive [ height ]--;
if ( map_section_alive [ height ] == 0) {
mulset.erase(height);
}
}
}
int highest = *(mulset.cbegin());
//cout<<highest<<endl;
if (temp[2] == -1) {
temp[0] = p[i];
temp[2] = highest;
continue;
}
if (highest != temp[2]) {
temp[1] = p[i];
res.push_back(temp);
temp[0] = p[i];
temp[2] = highest;
}
}
return res;
}
};