仓鼠群的每周题目如下
先上代码,因为目前正在用swift作主要语言开发,所以用swift来解答
//swift版本
class Solution {
func surfaceArea(_ grid: [[Int]]) -> Int {
var res: Int = 0
for i in 0..<grid.count {
for v in grid[i] {
if v == 0 {
continue
}
res += (4*v + 2)
}
}
//去重
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if (i == grid.count - 1) {
if j == (grid[i].count - 1) {
continue
}
res -= min(grid[i][j], grid[i][j+1]) * 2
}
else {
if j == (grid[i].count - 1) {
res -= min(grid[i][j], grid[i+1][j]) * 2
continue
}
res -= min(grid[i][j], grid[i][j+1]) * 2
res -= min(grid[i][j], grid[i+1][j]) * 2
}
}
}
return res
}
}
思路大致如下,
1.先计算每个网格摞起来的小立方体的表面积,即grid[i][j]的总表面积。累加计算所有单个网格的总表面积, 本人思路,每个立方体前后左右都有4个,再加上最底层和最顶层的,每个网格总共4v+2
2.再遍历去重:判断grid[i][j]和其相邻的网格表面积,用总表面积减去这些重复计算的面积,即得到所求值