该题难度为一个困难
该题思路为单调栈:所谓单调栈就是一个单调递增或单调递减的单调队列。
思路取自于b站该博主:小姐姐刷题-Leetcode 84 柱状图中最大的矩形_哔哩哔哩_bilibili
class Solution {
public:
int largestRectangleArea(vector<int>& heights)
{
if (heights.empty())
{
return 0;
}
if (heights.size() == 1)
{
return heights[0];
}
stack<int> stack;
int res = 0;//最后返回的面积存入到res中
heights.push_back(0);
heights.insert(heights.begin(), 0);
for (int i = 0; i < heights.size(); ++i)
{
if (stack.empty() || heights[i] >= heights[stack.top()])
{
stack.push(i);
}
else if (heights[i] < heights[stack.top()])
{
while (!stack.empty() && heights[i] < heights[stack.top()])
{
int height = heights[stack.top()];
stack.pop();
int wide = i - stack.top() - 1;
res = max(res, height * wide);
}
stack.push(i); //将在stack中的值pop出去之后 再将下标i添加到stack中
}
}
return res;
}
};
这道题扣了好久
在算法这条路上还是任重道远啊!!!