做网站横幅用什么软件好老王搜索引擎入口
文章目录
- Leetcode 84.柱状图中最大的矩形
Leetcode 84.柱状图中最大的矩形
题目链接:Leetcode 84.柱状图中最大的矩形
题目描述: 给定 n
个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1
。求在该柱状图中,能够勾勒出来的矩形的最大面积。
思路: 我们发现:数组中的每个元素,若假定以它为高,能够展开的宽度越宽,那么以它为高的矩形面积就越大。因此需要找到每个元素左边第一个比它矮的矩形和右边第一个比它矮的矩形,在这中间的就是最大宽度。 与Leetcode 42. 接雨水不同的是,本题的单调栈顺序:栈头到栈底从大到小。
代码如下:
class Solution {
public:int largestRectangleArea(vector<int>& heights) {int result = 0;stack<int> st;// 将数组首尾加上0,避免因为栈空而跳过计算逻辑heights.insert(heights.begin(), 0);heights.push_back(0);st.push(0); // 栈内存放下标for (int i = 1; i < heights.size(); i++) {if (heights[i] >= heights[st.top()]) {st.push(i);} else {while (!st.empty() && heights[i] < heights[st.top()]) {int mid = st.top();st.pop();if (!st.empty()) {int l = st.top();int r = i;int w = r - l - 1;int h = heights[mid];result = max(result, w * h);}}st.push(i);}}return result;}
};
当我们对单调栈代码逻辑熟悉之后,刷题时可以直接依照模板来写:
stack<int> st;
for(int i = 0; i < nums.size(); i++)
{while(!st.empty() && st.top() > nums[i]){st.pop();}st.push(nums[i]);
}
总结: 单调栈还需要多刷题,仅仅掌握几道经典题目是不够的。
最后,如果文章有错误,请在评论区或私信指出,让我们共同进步!