• LeetCode 84. Largest Rectangle in Histogram


    原题链接在这里:https://leetcode.com/problems/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.

    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.

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

    题解: 

    用stack保存数组的index, 确保stack中index对应的高度是递增的.

    当出现较小高度时需要不停的pop出比它大的index, 更新最大面积. 

    如何更新呢. 高度是heights[stk.pop()], 宽度是stk pop后的顶部index, stk.peek()到i之间的距离-1.

    最后在从后到前更新次最大面积.

    Time Complexity: O(n). n = heights.length. 

    Space: O(n).

    AC Java:

     1 class Solution {
     2     public int largestRectangleArea(int[] heights) {
     3         if(heights == null || heights.length == 0){
     4             return 0;
     5         }
     6         
     7         int res = 0;
     8         Stack<Integer> stk = new Stack<Integer>();
     9         stk.push(-1);
    10         
    11         for(int i = 0; i<heights.length; i++){
    12             while(stk.peek()!=-1 && heights[stk.peek()]>=heights[i]){
    13                 int h = heights[stk.pop()];
    14                 res = Math.max(res, h*(i-stk.peek()-1));        
    15             }
    16             
    17             stk.push(i);
    18         }
    19         
    20         while(stk.peek()!=-1){
    21             res = Math.max(res, heights[stk.pop()]*(heights.length-stk.peek()-1));
    22         }
    23                            
    24         return res;        
    25     }
    26 }
  • 相关阅读:
    html5 canvas 小例子 旋转的时钟
    用深度学习(CNN RNN Attention)解决大规模文本分类问题
    生成式对抗网络GAN 的研究进展与展望
    linux 系统信息查看
    cmd 更改字体
    查看sbt版本
    机器学习算法汇总
    spark 大数据 LR测试
    spark
    hadoop生态圈介绍
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824943.html
Copyright © 2020-2023  润新知