1.每日温度
739. 每日温度
入栈,循环与栈顶比较,若小则入栈,若大则记录答案并出栈
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
r = [0]*len(temperatures)
stack = []
for i in range(len(temperatures)):
while len(stack)>0 and temperatures[i]>temperatures[stack[-1]]:
r[stack[-1]]=i-stack[-1]
stack.pop()
stack.append(i)
return r
2.下一个更大元素 I
496.下一个更大元素 I
与1相比,记录答案前先搜索当前值是否在nums1中
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
r = [-1]*len(nums1)
stack = [0]
for i in range(1,len(nums2)):
while len(stack)>0 and nums2[i]>nums2[stack[-1]]:
if nums2[stack[-1]] in nums1:
r[nums1.index(nums2[stack[-1]])]=nums2[i]
stack.pop()
stack.append(i)
return r
3.下一个更大元素II
503.下一个更大元素II
与1相比,整个数组处理两次即可
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
r = [-1]*len(nums)
nums = nums+nums
stack = []
for i in range(len(nums)):
while len(stack)>0 and nums[i]>nums[stack[-1]]:
if stack[-1]>=len(r):
r[stack[-1]-len(r)] = nums[i]
else:
r[stack[-1]] = nums[i]
stack.pop()
stack.append(i)
return r
4.接雨水
42. 接雨水
双指针
按列算,每列可以接雨水的值=min(左边最高列,右边最高列)-本列高度
单调栈
按行算,
若当前元素比栈顶元素小,入栈;
若当前元素比栈顶元素相等,出栈,再入栈;
若当前元素比栈顶元素大,循环尽此种情况,出栈记为mid,栈顶记为left,待入栈记为right,r=(min(right,left)-mid)*(ir-il-1)。
class Solution:
def trap(self, height: List[int]) -> int:
r = 0
stack = [0]
for i in range(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]]:
mid = stack[-1]
stack.pop()
if len(stack)>0:
left = stack[-1]
r += (min(height[i],height[left])-height[mid])*(i-left-1)
stack.append(i)
return r
5.柱状图中最大的矩形
84.柱状图中最大的矩形
对于每一列,找左边比它矮的坐标,和右边比它矮的坐标,ri=height[i]*(right-left-1)
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights = [0]+heights+[0]
r = 0
stack = [0]
for i in range(1,len(heights)):
if heights[i]>heights[stack[-1]]:
stack.append(i)
elif heights[i]==heights[stack[-1]]:
stack.pop()
stack.append(i)
else:
while len(stack)>0 and heights[i]<heights[stack[-1]]:
mid = stack[-1]
stack.pop()
if len(stack)>0:
left = stack[-1]
r = max(r,(i-left-1)*heights[mid])
stack.append(i)
return r