leetcode42.接雨水
class Solution {
public:int trap(vector<int>& height) {if(height.size()<=2) return 0;stack<int> st;st.push(0);int sum = 0;// 单调栈元素为索引// 单调栈从栈底开始为递减// 如果入栈元素 < 栈顶元素 则入栈;for(int i=1; i<height.size(); ++i){ while(!st.empty() && height[i] > height[st.top()]){ // 保留索引int mid = st.top();st.pop();if(!st.empty()){ // 计算高度int h = min(height[st.top()], height[i]) - height[mid];// 计算宽度int w = i - st.top() - 1;sum += h * w;}}st.push(i);}return sum;}
};
leetcode 84.柱状图中最大的矩形
class Solution {
public:int largestRectangleArea(vector<int>& heights) {heights.insert(heights.begin(), 0);heights.push_back(0);// 单调栈元素:索引// 单调栈顺序:从栈底到栈头递增stack<int> st;st.push(0);int max_square = heights[0];for(int i=1; i<heights.size(); ++i){while(!st.empty() && heights[i]<heights[st.top()]){int mid = st.top();cout << mid;st.pop();int h = heights[mid];int w = i - mid;max_square = max(max_square, w*h);}st.push(i);}return max_square;}
};
@代码随想录