Problem: 42. 接雨水
思路
利用单调栈找到左右两边第一个比当前柱子高的柱子,遍历所有柱子,
当前柱子能接的雨水为
为了避免同一个高度的的柱子重复统计,使用集合记录已经被统计过的柱子
在统计左边第一个比当前高的柱子的时候可以将数组反转,重复执行单调栈套路,如py代码所示
Code
C代码实现
#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int stk[N], tt = 0, l[N], r[N], v[N], n;
set<pair<int, int>> hasCount;
int main() {
cin >> n;
for(int i = 1;i <= n;i ++) cin >> v[i];
tt = 0;
for(int i = 1;i <= n;i ++) {
while(tt && v[stk[tt]] <= v[i]) tt --;
l[i] = stk[tt];
stk[++ tt] = i;
}
tt = 0;
for(int i = n;i > 0;i --) {
while(tt && v[stk[tt]] <= v[i]) tt --;
r[i] = stk[tt];
stk[++ tt] = i;
}
int res = 0;
for(int i = 1;i <= n;i ++) {
if(l[i] == 0 || r[i] == 0 || hasCount.find({l[i], r[i]}) != hasCount.end()) continue;
int w = r[i] - l[i] - 1, h = min(v[r[i]], v[l[i]]) - v[i];
hasCount.insert({l[i], r[i]});
res += w * h;
}
cout << res;
return 0;
}
Python代码实现
class Solution:
def trap(self, height: List[int]) -> int:
def get(arr: List[int]) -> List[int]:
stk, res = [], [-1 for _ in range(len(arr))]
for i, h in enumerate(arr):
while stk and arr[stk[-1]] < h:
res[stk.pop()] = i
stk.append(i)
return res
r, l = get(height), [h if h == -1 else len(height) - h - 1 for h in get(height[::-1])[::-1]]
st = set()
cnt = 0
for i in range(len(l)):
if l[i] == -1 or r[i] == -1 or (l[i], r[i]) in st: continue
length = r[i] - l[i] - 1
t = min(height[l[i]], height[r[i]]) - height[i]
cnt += t * length
st.add((l[i], r[i]))
return cnt
总结
单调栈,一般用于在o(n)查找右边第一个比当前位置大/小的值,并且套路固定