No.84 柱状图中最大的矩形

结果

法一:
截屏2019-10-24下午8.23.47.png

法二:
截屏2019-10-24下午8.29.24.png

思路

在这里插入图片描述

代码

解法一:

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int n = heights.size(),res = 0;
        for(int i = 0; i < n; ++i){
            int left = i,right = i;
            while(left >= 0 && heights[left] >= heights[i]) left--;
            while(right < n && heights[right] >= heights[i]) right++;
            res = (right - left - 1) * heights[i] > res ? (right - left - 1) * heights[i] : res;
        }
        return res;
    }
};

解法二:

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        if(heights.size() == 0) return 0;
        int n = heights.size(),res = heights[0],record;
        stack<int> st;
        st.push(-1);
        for(int i = 0; i < n; ++i){
            while(st.top()!=-1 && heights[i] < heights[st.top()]){
                int tmp = st.top();
                st.pop();
                res = max(heights[tmp] * (i - st.top() - 1),res);
            }
            st.push(i);
        }
        while(st.top()!=-1){
            int tmp = st.top();
            st.pop();
            res = max(heights[tmp] * (n - st.top() - 1),res);
        }
        return res;
    }
};

后记

She was still too young to know that life never gives anything for nothing, and that a price is always exacted for what fate bestows。

发布了9 篇原创文章 · 获赞 6 · 访问量 1023

猜你喜欢

转载自blog.csdn.net/Acher_zxj/article/details/102731476