单调栈
在python中,列表能实现栈的功能
stack.append(),stack.pop(),stack[-1]
1.最大温度

python
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
n = len(temperatures)
res = [0]*n
for i in range(n):
while stack and temperatures[i]>temperatures[ stack[-1]]:
index = stack.pop()
res[index] = i-index
stack.append(i)
return res
代码中注意两个部分,一个是while的条件,stack要不为空,用循环能够一次性找到多个匹配的下标,在每个循环的最后进行append
2.接雨水

这里用了跟上面一样的思路,重点在于不只弹出当前的,还要考虑左边的墙壁,遍历时while判断是否能作为右边的墙壁
算雨水总量的时候,是按照每个下标相加的
python
class Solution:
def trap(self, height: List[int]) -> int:
res = 0
n = len(height)
stack = []
for i in range(n):
h = height[i]
while stack and height[stack[-1]]<h:
top = stack.pop()
if not stack:
break
left = stack[-1]
w = i-left-1
h0 = min(h,height[left])-height[top]
res+=h0*w
stack.append(i)
return res
哈希

python
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n = len(nums)
for i in range(n):
while 1<=nums[i]<=n and nums[nums[i]-1]!=nums[i]:
index = nums[i]-1
nums[i],nums[index] = nums[index],nums[i]
for i in range(n):
if nums[i]!=i+1:
return i+1
return n+1
注意代码中在交换时只处理了在0-n范围内的数,我们需要不断地交换,直到当前位置 i 放了一个不属于 [1, N] 范围的废数,或者放了一个已经归位的正确数,才能继续处理下一个位置 i+1
每个元素最多只会被交换一次到它正确的位置上,一旦归位,就不会再被移动,所以总的交换次数绝对不会超过N次,均摊下来是严格的 O(n)

(目前做了这几题,后续会更新)