zoukankan      html  css  js  c++  java
  • 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.

    histogram

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

    histogram

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

    [思维问题]:

    [一句话思路]:

    小高度使得全部大高度都终结了,对POP出来的面积打擂台

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. stack.peek() == 0 时属于非空
    2. max要初始化为0
    3. 可以用height[stack.peek()]来运用数组
    4. i = 0; i <= height.length 都要打印 比如1 1 

    [二刷]:

    1. 用三元运算符,curt到头了应该是-1,width在栈为空时就是i本身
    2. 在括号里pop了也算是完成了pop,不用再pop了

    [总结]:

    [复杂度]:Time complexity: O(n) push了n个但是只会pop出来一个 Space complexity: O(n)

    [英文数据结构,为什么不用别的数据结构]:

    [其他解法]:

    [Follow Up]:

    85 1拼出的最大矩形

    [题目变变变]:

    public class Solution {
        public int largestRectangleArea(int[] height) {
            if (height == null || height.length == 0) {
                return 0;
            }
            
            Stack<Integer> stack = new Stack<Integer>();
            int max = 0;
            for (int i = 0; i <= height.length; i++) {
                int curt = (i == height.length) ? -1 : height[i];
                while (!stack.isEmpty() && curt <= height[stack.peek()]) {
                    int h = height[stack.pop()];
                    int w = stack.isEmpty() ? i : i - stack.peek() - 1;
                    max = Math.max(max, h * w);
                }
                stack.push(i);
            }
            
            return max;
        }
    }
    View Code
  • 相关阅读:
    flask连接数据库的URI书写格式
    touch事件中的touches、targetTouches和changedTouches
    postgresql自增字段初始值的设定
    ubuntu下使用apt-get install安装软件的安装位置
    微信小程序全局变量的设置、使用、修改
    微信小程序常用的3种提示弹窗
    vue练手项目——桌面时钟
    用原生JS实现爱奇艺首页导航栏
    vue-cli配置环境变量的方法
    cross-env解读
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8250154.html
Copyright © 2011-2022 走看看