标签:
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