当前位置: 首页> 汽车> 时评 > 代码随想录训练营day49|单调栈part2

代码随想录训练营day49|单调栈part2

时间:2025/7/12 6:59:24来源:https://blog.csdn.net/weixin_45831563/article/details/141607509 浏览次数: 0次

接雨水

力扣题目链接

class Solution {
public:int trap(vector<int>& height) {int h = 0;int result = 0;stack<int> st;//存index// st.push(0);for(int i = 0; i < height.size(); i++){if(!st.empty() && height[st.top()] <= height[i]){while(!st.empty() && height[st.top()] < height[i]){h = height[st.top()];st.pop();if(!st.empty()){int w = i-st.top()-1;int h2 = min(height[st.top()], height[i])-h;result += h2 * w;}} }st.push(i);}return result;}
};

柱状图中最大的矩形

力扣题目链接

class Solution {
public:int largestRectangleArea(vector<int>& heights) {int result = 0;unordered_map<int, int> umap;stack<int> st;// 栈内元素递增for(int i = 0; i < heights.size(); i++){if(st.empty() || heights[st.top()] < heights[i]){st.push(i);}else{int j;// 遇到更小的元素时弹出,将入栈元素的index变为出栈的元素的,这里用覆盖heights来实现while(!st.empty() && heights[st.top()] >= heights[i]){j = st.top();// 判断局部矩阵result = max(result, (i-j) * heights[j]);heights[j] = heights[i];st.pop();}st.push(j);}}// 将递增栈的元素弹出,栈内元素满足到heights.size()处为矩形while(!st.empty()){int j = heights.size();result = max(result, heights[st.top()] * (j - st.top()));st.pop();}return result;}
};
关键字:代码随想录训练营day49|单调栈part2

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: