什么是单调栈?顾名思义,栈中的元素按照某种方式排列,但必须是单调的,如果栈顶元素破坏了栈的单调性,就弹出该元素,直到栈顶元素满足栈的单调性为止。
功能用途:可以很方便地求出某元素左边或右边第一个比其大或小的元素,且时间复杂度为O(n)。
题目应用(Leecode 柱状图中最大的矩形):https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
class Solution {
public:
int largestRectangleArea(vector<int>& heights)
{
stack<int> hst; // the stack stores index of array.
heights.push_back(0); // in order to pop all elements
int maxArea = 0;
for (int i = 0; i < heights.size(); i++) {
while (!hst.empty() && heights[hst.top()] > heights[i]) {
int topIndex = hst.top();
hst.pop();
int width = (hst.empty() ? i : (i - hst.top() - 1));
if (maxArea < heights[topIndex] * width) {
maxArea = heights[topIndex] * width;
}
}
hst.push(i);
}
return maxArea;
}
};