python_day_13:20180815
887. 三维形体投影面积
在 N * N 的网格中,我们放置了一些与 x,y,z 三轴对齐的 1 * 1 * 1 立方体。
每个值 v = grid[i][j] 表示 v 个正方体叠放在单元格 (i, j) 上。
现在,我们查看这些立方体在 xy、yz 和 zx 平面上的投影。
投影就像影子,将三维形体映射到一个二维平面上。
在这里,从顶部、前面和侧面看立方体时,我们会看到“影子”。
返回所有三个投影的总面积。
https://leetcode-cn.com/problems/projection-area-of-3d-shapes/description/
思路:
先求底部占据的方块数,直接加1即可,再求grid中每个元素的最大值。grid本身是由列表组成的列表,所以他的子元素也是列表,可以用max函数。这样得到一个侧面的影面积。将grid转置后,再求一遍面积,得到另一个影面的面积。三个数相加即是所求。
class Solution:
def projectionArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
s=0
for i in grid:
for j in i:
if j>0:
s+=1
s+=self.shadow(grid)
newgrid=zip(*grid)
s+=self.shadow(newgrid)
return s
def shadow(self,grid):
s=0
for i in grid:
s+=max(i)
return s
326. 3的幂
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
思路:
如果一个数是3的幂,那么通过有限次的除以三,最终一定会得到尾数为1
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n==0:
return False
while n%3==0:
n/=3
return n==1
342. 4的幂
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
https://leetcode-cn.com/problems/power-of-four/description/
思路:
和3的幂思路类似。
class Solution:
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
if num==1:
return True
if num ==0:
return False
while num%4==0:
num/=4
return num==1

浙公网安备 33010602011771号