栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

力扣1840——最高建筑高度(贪心)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣1840——最高建筑高度(贪心)






找到真正的限制是关键

解题思路

如果高度限制就是建筑物的高度,那么最大值就很好求了;
朴素的思路是多源BFS,但数据量太大,肯定不能求出每个建筑物的高度;
所以可以贪心的只求确定高度建筑范围内的最大值;
分情况讨论后可归纳公式为max(height, last_height) + (dis - abs(height - last_height)) / 2;

但是给出的限制并不是真实的限制,会虚高,真实的限制只会更低;
左边的限制会影响右边的限制,同时右边也会影响左边;
左右两边的高度差最大不能超过其距离差(相邻位置最大高度差为1);

所以从左到右,再从右到左,将虚高的限制降低;
最左边限制为位置1高度0,最右边为位置n高度n-1;

因为给出的建筑并非有序,所以需要先按位置升序排一下;

代码
class Solution {
public:
    int maxBuilding(int n, vector>& restrictions) {
        sort(restrictions.begin(), restrictions.end());
        int rsize = restrictions.size();
        int last_pos = 1, last_height = 0;
        int ans = 0;
        for(int i = 0; i < rsize; i++) {
            int pos = restrictions[i][0], height = restrictions[i][1];
            int dis = pos - last_pos;
            if(height > last_height + dis) restrictions[i][1] = last_height + dis;
            last_pos = pos; last_height = restrictions[i][1];
        }
        last_pos = n; last_height = n - 1;
        for(int i = rsize - 1; i >= 0; i--) {
            int pos = restrictions[i][0], height = restrictions[i][1];
            int dis = last_pos - pos;
            if(height > last_height + dis) restrictions[i][1] = last_height + dis;
            last_pos = pos; last_height = restrictions[i][1];
        }
        //for(auto r : restrictions) cout << r[0] << r[1] << endl;
        last_pos = 1; last_height = 0;
        for(int i = 0; i < rsize; i++) {
            int pos = restrictions[i][0], height = restrictions[i][1];
            int dis = pos - last_pos;
            ans = max(ans, max(height, last_height) + (dis - abs(height - last_height)) / 2);
            last_pos = pos; last_height = height;
        }
        return max(ans, last_height + n - last_pos);       
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/744374.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号