#84 Largest Rectangle in Histogra——Top 100 Liked Questions

﹏ヽ暗。殇╰゛Y 2022-01-23 01:47 232阅读 0赞

Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

histogram.png
Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3].

histogram_area.png
The largest rectangle is shown in the shaded area, which has area = 10 unit.

Example:

  1. Input: [2,1,5,6,2,3]
  2. Output: 10

第一次:暴力解法,时间超时:遍历每个元素,设定两个指针left和right,初始值均为i,找height[i]两边比其大的元素,遇到比其小的就停止,当左右两边都没有比height[i]大的元素时,计算面积:height[i] * (right-left+1),并更新最大面积

  1. class Solution(object):
  2. def largestRectangleArea(self, heights):
  3. """
  4. :type heights: List[int]
  5. :rtype: int
  6. """
  7. if not heights:
  8. return 0
  9. m = len(heights)
  10. res = 0
  11. for i in range(0, m):
  12. left, right = i, i
  13. while left - 1 >= 0 and heights[left - 1] >= heights[i]:
  14. left = left - 1
  15. while right + 1 <= m - 1 and heights[right + 1] >= heights[i]:
  16. right = right + 1
  17. area = heights[i] * (right - left + 1)
  18. res = max(area, res)
  19. return res

Time Limit Exceeded

第二次:采用单调栈

  1. class Solution(object):
  2. def largestRectangleArea(self, heights):
  3. """
  4. :type heights: List[int]
  5. :rtype: int
  6. """
  7. if not heights:
  8. return 0
  9. heights.append(0)
  10. stack = [-1]
  11. L = len(heights)
  12. ans = 0
  13. for i in range(L):
  14. while heights[i] < heights[stack[-1]]:
  15. h = heights[stack.pop()]
  16. w = i - stack[-1] - 1
  17. ans = max(ans, h * w)
  18. stack.append(i)
  19. return ans

Runtime: 84 ms, faster than 70.78% of Python online submissions forLargest Rectangle in Histogram.

Memory Usage: 13.5 MB, less than 73.96% of Python online submissions for Largest Rectangle in Histogram.

发表评论

表情:
评论列表 (有 0 条评论,232人围观)

还没有评论,来说两句吧...

相关阅读