leetcode84:Largest Rectangle in Histogram

朴灿烈づ我的快乐病毒、 2022-05-11 14:36 288阅读 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

求直方图中的最大矩形面积。

这里利用单调栈的方法,单调栈中保存heights的index,要始终保持单调栈中的index对应的高度heights是不递减的。

index从heights数组开始遍历,每次最大限度的将heights的index入栈(heights[index] heights[栈顶]),然后进行出栈操作。

一直出栈到heights[index] >= heights[栈顶]或者栈空为止,每个元素p出栈后,计算一下可能的最大面积,高度h是heights[p];

宽度w是index - height[栈顶] - 1,面积就是h * w。注意宽度的计算,不能是index - height[p],因为已经出栈的p和当前栈顶元素可能不是连续的,他们中间可能有更高的heights被出栈了。

另外注意栈空的情况,宽度就变成了index,栈空表明刚出栈的p的heights[p]是index前面最小的,所以宽度是index。

  1. func largestRectangleArea(height []int) int {
  2. n := 0
  3. if n = len(height); n == 0 {
  4. return 0
  5. }
  6. ans := 0
  7. stack := make([]int, n)
  8. for i := 0; i < n; i++ {
  9. if isEmpty(stack) || height[top(stack)] <= height[i] {
  10. stack = append(stack, i) //这里入栈的是index,不是height[index]
  11. continue
  12. }
  13. for !isEmpty(stack) && height[top(stack)] > height[i] {
  14. pos := pop(stack)
  15. stack = stack[:len(stack) - 1]
  16. Height := height[pos]
  17. var Width int
  18. if isEmpty(stack) {
  19. Width = i
  20. } else {
  21. Width = i - top(stack) - 1
  22. }
  23. if ans < Height * Width {
  24. ans = Height * Width
  25. }
  26. }
  27. i-- //减一将当前的index入栈
  28. }
  29. fmt.Println("here")
  30. for !isEmpty(stack) {
  31. pos := pop(stack)
  32. stack = stack[:len(stack) - 1]
  33. Height := height[pos]
  34. var Width int
  35. if isEmpty(stack) {
  36. Width = n
  37. } else {
  38. Width = n - top(stack) - 1
  39. }
  40. if ans < Height * Width {
  41. ans = Height * Width
  42. }
  43. }
  44. return ans
  45. }
  46. func top(stack []int) int {
  47. return stack[len(stack) - 1]
  48. }
  49. func isEmpty(stack []int) bool {
  50. if len(stack) == 0 {
  51. return true
  52. }
  53. return false
  54. }
  55. func pop(stack []int) (int) {
  56. ret := stack[len(stack) - 1]
  57. return ret
  58. }

发表评论

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

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

相关阅读