下一个更大元素(可循环)
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# 做了两遍遍历,相当于循环
dp = [-1] * len(nums)
stack = []
for i in range(len(nums)*2):
while(len(stack) != 0 and nums[i%len(nums)] > nums[stack[-1]]):
dp[stack[-1]] = nums[i%len(nums)]
stack.pop()
stack.append(i%len(nums))
return dp
接雨水
每个柱子之间是没有空隙的
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
result=0
stack=[0]
for i in range(1,len(height)):
if height[i] < height[stack[-1]]:
stack.append(i)
elif height[i] == height[stack[-1]]:
stack.pop()
stack.append(i)
else:
while len(stack) !=0 and height[i] > height[stack[-1]]:
cur_height=height[stack[-1]]
stack.pop()
if stack:
right_height=height[i]
left_height=height[stack[-1]]
h=min(left_height,right_height)-cur_height
w=i-stack[-1]-1
result += h*w
stack.append(i)
return result