您的位置:首页 > 其它

[LeetCode] The Skyline Problem

2015-07-13 23:10 302 查看
An interesting problem! But not very easy at first glance. You need to think very clear about how will a keypoint be generated. Since I only learn from others' solutions and am still unable to give my personal explanations, I would suggest you to these solutions: C++ priority_queue solution, Python heapq solution. Of course, there is still a divide-and-conquer solution on Geeksforgeeks.com, which is much more difficult to understand :-)

Well, I just rewrite the code in the first solution as follows, by giving those variables more meaning names to help understand it.

class Solution {
public:
vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
int idx = 0, start, height, n = buildings.size();
vector<pair<int, int> > skyline;
priority_queue<pair<int, int> > liveBuildings;
while (idx < n || !liveBuildings.empty()) {
if (liveBuildings.empty() || idx < n && buildings[idx][0] <= liveBuildings.top().second) {
start = buildings[idx][0];
while (idx < n && buildings[idx][0] == start) {
liveBuildings.push(make_pair(buildings[idx][2], buildings[idx][1]));
idx++;
}
}
else {
start = liveBuildings.top().second;
while (!liveBuildings.empty() && liveBuildings.top().second <= start)
liveBuildings.pop();
}
height = liveBuildings.empty() ? 0 : liveBuildings.top().first;
if (skyline.empty() || skyline.back().second != height)
skyline.push_back(make_pair(start, height));
}
return skyline;
}
};


The Python translation is as follows. Note that since the default heapq is a min heap, we take the negative of the left and right positions and the height of buildings.

class Solution:
# @param {integer[][]} buildings
# @return {integer[][]}
def getSkyline(self, buildings):
idx, n = 0, len(buildings)
liveBuildings, skyline = [], []
while idx < n or len(liveBuildings) > 0:
if len(liveBuildings) == 0 or (idx < n and buildings[idx][0] <= -liveBuildings[0][1]):
start = buildings[idx][0]
while idx < n and buildings[idx][0] == start:
heapq.heappush(liveBuildings, [-buildings[idx][2], -buildings[idx][1]])
idx += 1
else:
start = -liveBuildings[0][1]
while len(liveBuildings) > 0 and -liveBuildings[0][1] <= start:
heapq.heappop(liveBuildings)
height = len(liveBuildings) and -liveBuildings[0][0]
if len(skyline) == 0 or skyline[-1][1] != height:
skyline.append([start, height])
return skyline
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: