首页 > 其他 > 详细

[LeetCode] The Skyline Problem

时间:2015-07-13 23:50:43      阅读:336      评论:0      收藏:0      [点我收藏+]

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.

 1 class Solution {
 2 public:
 3     vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
 4         int idx = 0, start, height, n = buildings.size();
 5         vector<pair<int, int> > skyline;
 6         priority_queue<pair<int, int> > liveBuildings;
 7         while (idx < n || !liveBuildings.empty()) {
 8             if (liveBuildings.empty() || idx < n && buildings[idx][0] <= liveBuildings.top().second) {
 9                 start = buildings[idx][0];
10                 while (idx < n && buildings[idx][0] == start) {
11                     liveBuildings.push(make_pair(buildings[idx][2], buildings[idx][1]));
12                     idx++;
13                 }
14             }
15             else {
16                 start = liveBuildings.top().second;
17                 while (!liveBuildings.empty() && liveBuildings.top().second <= start)
18                     liveBuildings.pop();
19             }
20             height = liveBuildings.empty() ? 0 : liveBuildings.top().first;
21             if (skyline.empty() || skyline.back().second != height)
22                 skyline.push_back(make_pair(start, height));
23         }
24         return skyline;
25     }
26 };

 

[LeetCode] The Skyline Problem

原文:http://www.cnblogs.com/jcliBlogger/p/4644209.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!