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

Leetcode 218 The Skyline Problem

时间:2015-06-25 17:27:51      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:leetcode   stl   multiset   

1. 问题描述

  
技术分享

Notes:

  • The number of buildings in any input list is guaranteed to be in the range [0, 10000].
  • The input list is already sorted in ascending order by the left x position Li.
  • The output list must be sorted by the x position.
  • There must be no consecutive horizontal lines of equal height in the output skyline. For instance, […[2 3], [4 5], [7 5], [11 5], [12 7]…] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: […[2 3], [4 5], [12 7], …]

2. 方法与思路

  总得思路是:左右节点+multiset
  首先,将所有的buildings分为左右节点(左x坐标,高)和(右x坐标,高)分别存储到vector<pair<int,int>>的结构中。这里为了将左右分开处理,做节点的高用负数表示。
  然后,将节点坐标按x坐标排序。
  之后,循环遍历节点vector,将节点的高插入到multiset中,并判断之前的高是否与当前一样,若不一样则保存当前高度和x坐标。

思路借鉴了Eason Liu的技术博客,这里表示感谢!

class Solution {
public:
    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
        int i,j,pre,cur;
        vector<pair<int,int> > re,height;
        multiset<int> heap;

        for(i = 0; i < buildings.size(); i++)
        {
            height.push_back(pair<int,int>(buildings[i][0],-buildings[i][2]));  
            height.push_back(pair<int,int>(buildings[i][1], buildings[i][2]));
        }

        sort(height.begin(),height.end());

        heap.insert(0);
        pre = 0; cur = 0;

        for(i = 0; i < height.size(); i++)
        {
            if(height[i].second < 0)
                heap.insert(-height[i].second);
            else
                heap.erase(heap.find(height[i].second)); 

            cur = *heap.rbegin();//multiset中最后一个元素,height的最大值
            if(cur != pre)
            {
                re.push_back(pair<int,int>(height[i].first,cur));
                pre = cur;
            }
        }

        return re;
    }
};

Leetcode 218 The Skyline Problem

标签:leetcode   stl   multiset   

原文地址:http://blog.csdn.net/jeanphorn/article/details/46638289

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!