zoukankan      html  css  js  c++  java
  • 84. Largest Rectangle in Histogram(直方图最大面积 hard)

    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.

    用桟

     1 class Solution {
     2     public int largestRectangleArea(int[] heights) {
     3         Stack<Integer> stack = new Stack<Integer>();
     4         
     5         //array 扩容,在最后一位加上0
     6         int[] a = new int[heights.length+1];
     7         for(int i =0;i<heights.length;i++)
     8             a[i] = heights[i];
     9         a[heights.length]=0;
    10         //
    11         
    12         
    13         int answer = 0;
    14         int temp;
    15         for(int i = 0;i<a.length;){
    16             if(stack.isEmpty()||a[i]>a[stack.peek()]){//a[i]与桟顶元素比较
    17                 stack.push(i);
    18                 i++;
    19             }
    20             else{
    21                 temp = stack.pop();
    22                 answer = Math.max(answer,a[temp]*(stack.isEmpty()?i: i-stack.peek()-1));
    23                 //桟为空的时候,需要计算长度为i 高度从0到i最矮的(即桟中最小的元素,弹出后,桟就空了)
    24             }
    25         }
    26         return answer;
    27     }
    28 }
  • 相关阅读:
    语言相关
    一道简单DP题
    一道概率题
    Android CrashHandler
    一道简单数学题
    面试中遇到的随机题目
    VMWare 无损扩展磁盘大小
    Android 源码编译记录
    Android handler 内存泄露分析及解决方法
    Android 反编译
  • 原文地址:https://www.cnblogs.com/zle1992/p/8465563.html
Copyright © 2011-2022 走看看