题目
思路分析
题目要求:无序数组中缺失的最小正整数
动态编程
记录下来所有的状态值,不需要每一次都去重复计算
参考博客
代码展示
from typing import List
class Solution:
#暴力破解:遍历每一个数,寻找左边最大值和右边最大值
def trap(self, height: List[int]) -> int:
heightlen = len(height)
total =0
for i in range(1,heightlen-1):
print('------',i,height[i])
#找到左边的最高点
left = i-1
leftheightest=height[left]
while left>=0:
if height[left]>=leftheightest:
leftheightest = height[left]
left-=1
print('leftheightest',leftheightest)
#找到右边的最高点
right = i+1
rightheightest=height[right]
while right<heightlen:
print('right',right,'heightlen',heightlen)
if height[right]>=rightheightest:
rightheightest = height[right]
right+=1
print('rightheightest',rightheightest)
#最后结果加上当前的水量
print(height[i],leftheightest,rightheightest)
tongheight = min(rightheightest,leftheightest)
if tongheight-height[i]>0:
total += tongheight-height[i]
print('tongheight-height[i]',tongheight-height[i],'total',total)
return total
def trap2(self, height: List[int]) -> int:
if height==[]:
return 0
heightlen = len(height)
leftheighlist = [0 for i in range(heightlen)]
leftheighlist[0] = height[0]
rightheighlist = [0 for i in range(heightlen)]
rightheighlist[heightlen-1] = height[heightlen-1]
#记录每一个位置 左边最大值
#类似 动态规划中将每一个状态的值记录下来
for i in range(1,heightlen-1):
leftheighlist[i] = max(leftheighlist[i-1],height[i-1])
#记录每一个位置 右边最大值
for i in range(1,heightlen-1):
rightheighlist[heightlen-1-i] = max(rightheighlist[heightlen-i],height[heightlen-i])
print(leftheighlist)
print(rightheighlist)
res = 0
#方便 一次性计算
for i in range(1,heightlen-1):
if min(leftheighlist[i],rightheighlist[i])-height[i]>0:
res+=(min(leftheighlist[i],rightheighlist[i])-height[i])
return res
if __name__ == "__main__":
a = Solution()
print(a.trap2([0,1,0,2,1,0,1,3,2,1,2,1]))