503、下一个更大元素II:
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
stack = []
res = [-1] * len(nums)
stack.append(0)
for i in range(1, len(nums)*2):
i %= len(nums)
if nums[i] <= nums[stack[-1]]:
stack.append(i)
else:
while stack and nums[i] > nums[stack[-1]]:
res[stack[-1]] = nums[i]
stack.pop(-1)
stack.append(i)
return res
关键点在于对于循环数组,思路是两个同样数组头尾相连,遍历新数组过程中对下标I取模计算
42、接雨水:
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
stack = [0]
sum = 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 stack and height[i] > height[stack[-1]]:
mid = stack.pop()
if not stack:
continue
h = min(height[i], height[stack[-1]]) - height[mid]
v = i - stack[-1] - 1
sum += h * v
stack.append(i)
return sum
这个题的关键是要弄明白,到底是纵向求和,还是横向求解,单调栈解法是横向求解,而暴力(双指针法)则是纵向求解