单调栈-原理与应用

单调栈---顾名思义,栈,且是单调的-单调递增或递减。

该算法模型能用来解决一类特定的问题,找该位置(左边和右边距离最近的比其大或比其小的元素)。

典型的问题有:下一个更大元素III接雨水最大矩形柱状图最大矩阵等。

代码具有典型的套路,下面贴出接雨水的代码: 

 1 int trap(vector<int>& height) {
 2         int res = 0;
 3         stack<int> s;
 4         int sz = height.size();
 5 
 6         for (int i = 0; i < sz; ++i) {
 7             while (!s.empty() && height[s.top()] < height[i]) {
 8                 int t = s.top();
 9                 s.pop();
10                 if (s.empty()) {
11                     break;
12                 }
13                 //int left = s.top();
14                 res += (min(height[s.top()], height[i]) - height[t]) * (i - s.top() - 1);
15             }
16             s.push(i);
17         }
18         
19         return res;
20     }

多做,多刷,多想,理解方能随机应变。

牢记套路模板。

     

  

posted @ 2022-05-02 15:38  Ray-ss  阅读(72)  评论(0编辑  收藏  举报