zoukankan      html  css  js  c++  java
  • leetcode| 84. 柱状图中最大的矩形

    ##给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。求在该柱状图中,能够勾勒出来的矩形的最大面积。 ![](https://img2018.cnblogs.com/blog/1805130/202002/1805130-20200212154827325-1450873595.png) 以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。 ![](https://img2018.cnblogs.com/blog/1805130/202002/1805130-20200212155256180-616019814.png) 图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。

    示例:
    输入: [2,1,5,6,2,3]
    输出: 10

    思路

    分治法:maxArea = max(当前区间minHeight*区间长度, max(minIndex左侧区间子问题, minIndex右侧区间子问题))
    时间复杂度O(nlgn),最坏O(n²),空间复杂度O(n)。

    代码

    class Solution {
        public int calcArea(int[] heights, int start, int end) {
    		if(end < start) return 0;
    		int minIndex = start;
    		int minHeight = heights[start];
    		for(int i = start+1; i <= end; i++) {
    			if(heights[i] < minHeight) {
    				minHeight = heights[i];
    				minIndex = i;
    			}
    		}
    		return Math.max(minHeight*(end-start+1), Math.max(calcArea(heights,start,minIndex-1),calcArea(heights,minIndex+1,end)));
    	}
    	
        public int largestRectangleArea(int[] heights) {
            return calcArea(heights, 0, heights.length-1);
        }
    }
    

    笔记

    存在栈方法,时间复杂度O(n),空间复杂度O(n)。

    链接:https://leetcode-cn.com/problems/largest-rectangle-in-histogram

  • 相关阅读:
    centos7配置vsftpd
    vsftpd上传文件出现553 Could not create file错误解决方法
    mysql表引擎myisam改为innodb
    python字符串
    linux虚拟机设置本地yum源
    python3读取excel数据
    expect远程登录服务器并执行命令
    sed中支持变量的处理方法
    test
    test
  • 原文地址:https://www.cnblogs.com/ustca/p/12299405.html
Copyright © 2011-2022 走看看