84. Largest Rectangle in Histogram. 单调栈

Posted xgbt

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了84. Largest Rectangle in Histogram. 单调栈相关的知识,希望对你有一定的参考价值。

Given n non-negative integers representing the histogram‘s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

技术图片

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

技术图片

The largest rectangle is shown in the shaded area, which has area = 10 unit.

Example:

Input: [2,1,5,6,2,3]
Output: 10

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-rectangle-in-histogram

1.vecotr几个声明

vector <int> vec;          //声明一个int型向量
vector <int> vec(5);       //声明一个初始大小为5的int向量
vector <int> vec(10, 1);   //声明一个初始大小为10且值都是1的向量

2.解题思路
遍历每个木板,对每一块木板分别向左向右拓展,知道遇见比自身低的木板,然后用高度?宽度。
使用栈进行求解,从左到右遍历,栈空则入栈,若栈非空,检查栈顶,若栈顶大于等于自身则出栈,直至栈空或者栈顶小于自身。此时栈顶元素的下标即为向左可拓展的最大下标,向右同理。
3.两次遍历改一次遍历
从左向右遍历,出栈时,当前元素下标即为出栈元素的向右可拓展的最大下标。

//2次遍历
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int n = heights.size();
        vector <int> left(n),right(n);
        int ans = 0;
        stack <int> st;

        for (int i = 0;i < n; i++){
            while ( !st.empty() && heights[i] <= heights[st.top()] ){
                st.pop();
            }
            left[i] = st.empty() ? -1 : st.top();
            st.push(i);
        }

        while (!st.empty()) st.pop();

        for (int i = n-1; i >=0 ; i--){
            while ( !st.empty() && heights[i] <= heights[st.top()] ){
                st.pop();
            }
            right[i] = st.empty() ? n : st.top();
            st.push(i);
        }

        for (int i = 0; i < n; i++){
            ans = max( ans, heights[i] * (right[i] - left[i] - 1));
        }

        return ans;
    }
};
//1次遍历
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int n = heights.size();
        vector <int> left(n,0),right(n,n);
        int ans = 0;
        stack <int> st;

        for (int i = 0;i < n; i++){
            while (!st.empty() && heights[st.top()] >= heights[i]){
                right[st.top()] = i;
                st.pop();
            }
            left[i] = st.empty() ? -1 : st.top();
            st.push(i);
        }

        for (int i = 0; i < n; i++){
            ans = max ( ans, heights[i] * (right[i] - left[i] -1));
        }

        return ans;
    }
};






以上是关于84. Largest Rectangle in Histogram. 单调栈的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 84. Largest Rectangle in Histogram

leetcode 84. Largest Rectangle in Histogram

84. Largest Rectangle in Histogram. 单调栈

84. Largest Rectangle in Histogram. 单调栈

leetcode 84. Largest Rectangle in Histogram

Leetcode 84: Largest Rectangle in Histogram