zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第84题:给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 求在该柱状图中,能够勾勒出来的矩形的最大面积。

    题目:
    给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。  求在该柱状图中,能够勾勒出来的矩形的最大面积。
    思路:
    自己想的方法类似于接雨水的问题,但是计算量在有的例子的时候太大,超时了,参考的别人的方法,就是使用栈和哨兵的思路,这个思路的程序设计的很巧妙。
    程序1:
    class Solution:
        def largestRectangleArea(self, heights: List[int]) -> int:
            length = len(heights)
            if length <= 0:
                return 0
            if length == 1:
                return heights[0]
            heights.append(0)
            stack = [-1]
            max_area = 0
            for index in range(length):
                while stack[-1] != -1 and heights[stack[-1]] >= heights[index]:
                    max_area = max(max_area, heights[stack.pop()] * (index - stack[-1] -1))
                stack.append(index)
            while stack[-1] != -1:
                max_area = max(max_area, heights[stack.pop()] * (length - stack[-1] - 1))
            return max_area
    程序2:
    class Solution:
        def largestRectangleArea(self, heights: List[int]) -> int:
            result = 0
            length = len(heights)
            for i in range(length):
                left_i = i
                right_i = i
                while left_i >= 0 and heights[left_i] >= heights[i]:
                    left_i -= 1
                while right_i < length and heights[right_i] >= heights[i]:
                    right_i += 1
                result = max(result, (right_i - left_i - 1) * heights[i])
            return result
  • 相关阅读:
    ACR Code Pacs
    如何利用IIS调试ASP.NET网站程序详解
    Server 2003 操作系统位数
    App.config/Web.config 中特殊字符的处理
    IE 对象不支持“attachEvent”属性或方法
    Invoke和BeginInvoke理解
    升级mongodb数据库2.6.6到3.0.3,切换引擎,主从同步数据
    mac android sdk manager 无法更新(被墙)
    hadoop-mongo map/reduce java
    mongodb use where and custom function to query mongodb存储过程
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12762844.html
Copyright © 2011-2022 走看看