题意:
给定一个数组heights,长度为n,height[i]是在第i点的高度,那么height[i]表示的直方图,能够形成的最大矩形是多少?
1.每个直方图宽度都为1
2.直方图都是相邻的
3.如果不能形成矩形,返回0即可
4.保证返回的结果不会超过 int
方法一:
中心拓展法
思路:二重循环。
外层循环遍历中心点,内层循环从中心点向左右两边拓展。
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n=heights.size();
int res=0;
for(int i=0;i<n;i++){//中心拓展法
int j=i-1,k=i+1;
while(j>=0&&heights[j]>=heights[i]){//向左边拓展
j--;
}
while(k<n&&heights[k]>=heights[i]){//向右边拓展
k++;
}
res=max(res,(k-j-1)*heights[i]);//维护最大值
}
return res;
}
};
时间复杂度:
空间复杂度:![]()
方法二:
单调栈
思路:单调栈。
维护一个单调递增的栈,栈存储的是值的下标(为了方便得到区间的大小)。
当栈非空并且栈顶数>=遍历到的数时,则弹栈并计算矩形的面积。
注意:在数组的最后追加一个值为0 的数,作用是弹出栈所有的元素。
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.push_back(0);//末尾追加一个0
int n=heights.size();
stack<int> st;//栈
int res=0;
for(int i=0;i<n;i++){
while(!st.empty()&&heights[st.top()]>=heights[i]){//栈非空并且栈顶数>=遍历到的数,则弹栈并计算矩形的面积
int t=st.top();
st.pop();
res=max(res,heights[t]*(st.empty()?i:i-st.top()-1));//维护最大值
}
st.push(i);
}
return res;
}
};
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号