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

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12762844.html