Leetcode 807. 保持城市天际线(学习一下求行列max值的求法即可)

核心思想:贪心,位置i,j上的建筑能够增加到的最大高度为当前行i上最高的建筑h1,和当前列j上最高的建筑h2去一个min即可,这样就可以不会影响边际线。

打卡代码

class Solution {
public:
    int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
        int n = grid[0].size();
        int N = 55;
        int res = 0;
        int col[N], row[N];
        // 求每一行的最大值
        for(int i = 0; i < n; i ++){
            int curmax = -1;
            for(int j = 0; j < n; j ++){
                if(grid[i][j] > curmax)
                    curmax = grid[i][j];
            }
            row[i] = curmax;
        } 
        // 求每一列的最大值
        for(int i = 0; i < n; i ++){
            int curmax = -1;
            for(int j = 0; j < n; j ++){
                if(grid[j][i] > curmax)
                    curmax = grid[j][i];
            }
            col[i] = curmax;
        }
        // 根据col和row索引出答案
        for(int i = 0; i < n; i ++){
            for(int j = 0; j < n; j ++){
                int t = 0;  // 当前位置需要增加的高度
                int curh = min(row[i], col[j]);
                // cout << curh << " ";
                t = curh - grid[i][j];
                res += t;
            }
        }
        return res;
    }
};

 优化一下求解每行/列求最大值的代码:

class Solution {
public:
    int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
        int n = grid[0].size();
        int N = 55;
        int res = 0;
        vector<int> col(n), row(n);
        // 求每一行的最大值.求每一列的最大值
        for(int i = 0; i < n; i ++){
            for(int j = 0; j < n; j ++){
                row[i] = max(row[i], grid[i][j]);
                col[j] = max(col[j], grid[i][j]);
            }
        } 
        // 根据col和row索引出答案
        for(int i = 0; i < n; i ++){
            for(int j = 0; j < n; j ++){
                int t = 0;  // 当前位置需要增加的高度
                int curh = min(row[i], col[j]);
                t = curh - grid[i][j];
                res += t;
            }
        }
        return res;
    }
};

相关推荐

  1. LeetCode399触发

    2024-07-18 17:42:02       30 阅读
  2. LeetCode 399:除法(图bfs遍历)

    2024-07-18 17:42:02       47 阅读
  3. Leetcode 150:逆波兰表达式

    2024-07-18 17:42:02       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-18 17:42:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-18 17:42:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-18 17:42:02       58 阅读
  4. Python语言-面向对象

    2024-07-18 17:42:02       69 阅读

热门阅读

  1. 在 Ubuntu上安装 Docker

    2024-07-18 17:42:02       25 阅读
  2. 爬虫的概念

    2024-07-18 17:42:02       21 阅读
  3. Vim 高手指南:Linux 环境下的高级使用技巧

    2024-07-18 17:42:02       18 阅读
  4. phpinfo

    2024-07-18 17:42:02       21 阅读
  5. 每天一个数据分析题(四百三十四)- t检验

    2024-07-18 17:42:02       22 阅读
  6. python \uxx字符串转中文

    2024-07-18 17:42:02       18 阅读
  7. Qt 中的多线程管理方法详解及示例

    2024-07-18 17:42:02       17 阅读
  8. Qt QJson组装数据Sig传递

    2024-07-18 17:42:02       19 阅读