代码随想录day60

84.柱状图中最大的矩形

双指针解法:超时

class Solution {
public:
    int largestRectangleArea(vector& heights) {
        int res=0;
        for(int i=0;i=0;left--){
                if(heights[left]

用数组提前记录一些信息,进行优化。

class Solution {
public:
    int largestRectangleArea(vector& heights) {
        vector minLeftIndex(heights.size());
        vector minRightIndex(heights.size());
        int size=heights.size();
        minLeftIndex[0]=-1;
        for(int i=1;i=0&&heights[t]>=heights[i]) t=minLeftIndex[t];
            minLeftIndex[i]=t;
        }
        minRightIndex[size-1]=size;
        for(int i=size-2;i>=0;i--){
            int t=i+1;
            while(t=heights[i]) t=minRightIndex[t];
            minRightIndex[i]=t;
        }
        int res=0;
        for(int i=0;i

单调栈:
关键点在于保持单调栈的单调递减,还有需要加强对于首尾加0的理解。

class Solution {
public:
    int largestRectangleArea(vector& heights) {
        int res=0;
        heights.insert(heights.begin(),0);
        heights.push_back(0);
        stack st;
        st.push(0);
        for(int i=1;iheights[st.top()]){
                st.push(i);
            }else if(heights[i]==heights[st.top()]){
                st.pop();
                st.push(i);
            }else{
                while(!st.empty()&&heights[i]

你可能感兴趣的:(算法,leetcode,数据结构)