码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] The Skyline Problem

时间:2015-07-13 23:53:14      阅读:180      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!