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
  • 相关阅读:
    在本地连接服务器上的mysql数据库
    js提取字符串中的数值
    下载安装mysql
    git最基础操作二(clone)
    点击页面出现富强、民主
    解决wepacke配置postcss-loader时autoprefixer失效问题
    li之间产生的间隙问题的解决方法
    webpack简单体验
    apply、call和bind
    remote Incorrect username or password ( access token)问题解决
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12762844.html
Copyright © 2011-2022 走看看