zoukankan      html  css  js  c++  java
  • Leetcode: 84. Largest Rectangle in Histogram

    Description

    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.

    Example

    Given heights = [2,1,5,6,2,3],
    return 10.
    

    思路

    • 假如已知数组为升序排列[1,2,3,5,8]

    • 则结果为(1 * 5) vs (2 * 4) vs (3 * 3) vs (5 * 2) vs (8 * 1),即通过升序方式来计算所有的面积,然后取最大值

    • 使用一个栈,来维护一个升序队列,如当前比栈顶大,直接入栈;比栈顶小,弹出并计算相应面积。注意判断栈为空的时候,即当前元素全部弹出去后,为空,此时应该怎么办。

    • 还有一种解释,即使用栈维护一个升序队列,如果当前小于栈顶,将栈顶弹出计算后,将栈顶替换为当前元素。画个图吧,容易理解。哈哈。

    代码

    class Solution {
    public:
        int largestRectangleArea(vector<int>& heights) {
            int len = heights.size();
            if(len == 0) return 0;
            
            stack<int> Stk;
            int res = -1, i = 0, index = 0, min_flag = INT_MAX;
            while(i < len){
               while(!Stk.empty() && heights[Stk.top()] > heights[i]){
                   int h = heights[Stk.top()];
                   Stk.pop();
                   
                   index = Stk.empty() ? i : i - Stk.top() - 1;
                   res = max(res, h * index);
               }
               Stk.push(i);
               i++;
            }
            
        
            while(!Stk.empty()){
                int h = heights[Stk.top()];
                Stk.pop();
                index = Stk.empty() ? len : len - Stk.top() - 1;          
                res = max(res, h * index);
            }
        
            return res;
        }
    };
    
  • 相关阅读:
    LeetCode: Trapping Rain Water
    LeetCode: Text Justification
    LeetCode: Unique Paths
    LeetCode: Unique Binary Search Trees
    向Google、Yahoo!和百度提交Sitemap网站地图
    Paypal IPN&PDT变量列表
    SQL查询和删除重复字段的内容
    [C#]基于.net技术的 Rss 订阅开发
    验证码识别流程
    c# string.Format 格式化日期
  • 原文地址:https://www.cnblogs.com/lengender-12/p/7003774.html
Copyright © 2011-2022 走看看