zoukankan      html  css  js  c++  java
  • 求柱状图中最大的矩形

    问题:

    # 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 
    #
    # 求在该柱状图中,能够勾勒出来的矩形的最大面积。

    方法一:暴力

    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution(object):
        def largestRectangleArea(self, heights):
            """
            :type heights: List[int]
            :rtype: int
            """
            length = len(heights)
            max_area = 0
            for i in range(length):
                min_height = math.inf
                for j in range(i, length):
                    min_height = min(min_height, heights[j])
                    area = min_height * (j-i+1)
                    max_area = max(area, max_area)
            return max_area
    # leetcode submit region end(Prohibit modification and deletion)

    方法二:优化,遍历每个柱子,左右扩展找满足条件的左柱和右柱

    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution(object):
        def largestRectangleArea(self, heights):
            """
            :type heights: List[int]
            :rtype: int
            """
            length = len(heights)
            max_area = 0
            for i in range(length):
                current_height = heights[i]
                left = right = i
                while (left-1 >= 0 and heights[left-1] >= current_height):
                    left -= 1
                while (right+1 < length and heights[right+1] >= current_height):
                    right += 1
                max_area = max(max_area, (right-left+1) * current_height)
            return max_area
    # leetcode submit region end(Prohibit modification and deletion)
    时刻记着自己要成为什么样的人!
  • 相关阅读:
    GDB+QEMU调试内核模块(实践篇)
    排序算法的python实现
    Linux命令行相关
    操作系统与网络
    计算机组成原理
    有了自己的技术博客
    if 和 if else
    十效率换算成十六进制
    <<左移 >>右移 >>>无符号右移 &与运算 |或运算 ^异或运算 ~反码
    // &与 // |或 // ^异或 // !非 // &&短路 // ||短路
  • 原文地址:https://www.cnblogs.com/demo-deng/p/14777449.html
Copyright © 2011-2022 走看看