LeetCode #807. Max Increase to Keep City Skyline 保持城市天际线
https://leetcode-cn.com/problems/max-increase-to-keep-city-skyline/
执行用时 : 3 ms, 在Max Increase to Keep City Skyline的Java提交中击败了95.31% 的用户 内存消耗 : 37.7 MB, 在Max Increase to Keep City Skyline的Java提交中击败了92.13% 的用户
最直接的思路:
- 获取矩阵的每一行最大值和每一列最大值
- 根据上述最大值来“提高”建筑
1 class Solution { 2 public int maxIncreaseKeepingSkyline(int[][] grid) { 3 int result = 0; 4 int rowSize = grid.length; 5 // rowMax 每行最大数值 6 int[] rowMax = new int[rowSize]; 7 8 int colSize = grid[0].length; 9 // colMax 每列最大数值 10 int[] colMax = new int[colSize]; 11 12 int i = 0; 13 int j = 0; 14 15 for (i = 0; i < rowSize; i++) { 16 rowMax[i] = 0; 17 for (j = 0; j < colSize; j++) { 18 if (grid[i][j] > rowMax[i]) { 19 rowMax[i] = grid[i][j]; 20 } 21 } 22 } 23 24 for (j = 0; j < colSize; j++) { 25 colMax[j] = 0; 26 for (i = 0; i < rowSize; i++) { 27 if (grid[i][j] > colMax[j]){ 28 colMax[j] = grid[i][j]; 29 } 30 } 31 } 32 33 for (i = 0; i < rowSize; i++) { 34 for (j = 0; j < colSize; j++) { 35 if (rowMax[i] > colMax[j]) { 36 result += colMax[j] - grid[i][j]; 37 } else { 38 result += rowMax[i] - grid[i][j]; 39 } 40 } 41 } 42 43 return result; 44 } 45 }