84:柱状图中最大的矩阵
题目链接:力扣
代码:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> st;
st.push(0);
int result = 0;
heights.insert(heights.begin(), 0); // 数组头部加入元素0
heights.push_back(0); // 数组尾部加入元素0
for(int i = 1; i < heights.size(); i++)
{
if(heights[i] > heights[st.top()])
{
st.push(i);
}else if(heights[i] == heights[st.top()])
{
st.pop();
st.push(i);
}else
{
while(!st.empty() && heights[i] < heights[st.top()])
{
int mid = st.top();
st.pop();
if(!st.empty())
{
int w = i - st.top() - 1;
int h = heights[mid];
result = max(result,w*h);
}
}
st.push(i);
}
}
return result;
}
};
找左右两边最小的 还有点不太熟
双指针法:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int result = 0;
vector<int> leftMin(heights.size(),0);
vector<int> RightMin(heights.size(),0);
leftMin[0] = -1;
RightMin[heights.size()-1] = heights.size();
for(int i = 1; i < heights.size(); i++)
{
int t = i-1;
while (t >= 0 && heights[t] >= heights[i])
t = leftMin[t];
leftMin[i] = t;
}
for(int i = heights.size()-2 ; i >= 0; i--)
{
int t = i+1;
while (t < heights.size() && heights[t] >= heights[i])
t = RightMin[t];
RightMin[i] = t;
}
for (int i = 0; i < heights.size(); i++) {
int sum = heights[i] * (RightMin[i] - leftMin[i] - 1);
result = max(sum, result);
}
return result;
}
};