其他分享
首页 > 其他分享> > LeetCode 0084 Largest Rectangle in Histogram

LeetCode 0084 Largest Rectangle in Histogram

作者:互联网

原题传送门

1. 题目描述

2. Solution 1

1、思路分析
方法1: 暴力方法(Time Limit Exceeded)
- 面积 = 底 x 高
- 固定底,求最大高度不好求
- 固定高,求最长底边好求
- 从i向两边遍历,找到左边和右边第1个严格小于height[i]的时候停下,中间的长度就是最长底边

2、代码实现

package Q0099.Q0084LargestRectangleInHistogram;

public class Solution1 {
    /*
      方法1: 暴力方法
       - 面积 = 底 x 高
       - 固定底,求最大高度不好求
       - 固定高,求最长底边好求
       - 从i向两边遍历,找到左边和右边第1个严格小于height[i]的时候停下,中间的长度就是最长底边
       时间复杂度度: O(n^2),空间复杂度: O(1)
     */
    public int largestRectangleArea1(int[] heights) {
        int len = heights.length;
        int ans = 0;
        for (int cur = 0; cur < len; cur++) { // 枚举高
            int height = heights[cur];
            int left = cur, right = cur;
            while (left - 1 >= 0 && heights[left - 1] >= height) {
                --left;
            }
            while (right + 1 < len && heights[right + 1] >= height) {
                ++right;
            }
            ans = Math.max(ans, (right - left + 1) * height);
        }
        return ans;
    }
}

3、复杂度分析
时间复杂度: O(n^2)
空间复杂度: O(1)

3. Solution 2

1、思路分析
单调栈。示例: heights = [2,1,5,6,2,3]。

2、代码实现

package Q0099.Q0084LargestRectangleInHistogram;

import java.util.ArrayDeque;
import java.util.Deque;

public class Solution2 {

    /*
      方法2: 单调栈
      area of rectangle include heights[i] is:
      (index of nextSmaller - index of previousSmaller - 1) * heights[i]

      回顾方法1,用数组遍历的视角来看
        left是指前一个小于当前高度的下标(index of previousSmaller)
        right是指下一个小于当前高度的下标(index of nextSmaller)
    */
    public int largestRectangleArea(int[] heights) {
        int len = heights.length;
        Deque<Integer> s = new ArrayDeque<>();
        int maxArea = 0;
        for (int i = 0; i <= len; i++) {
            int h = (i == len ? 0 : heights[i]);
            if (s.isEmpty() || h >= heights[s.peek()]) {
                s.push(i);
            } else {
                int tp = s.pop();
                int width = (s.isEmpty() ? i : i - 1 - s.peek());
                maxArea = Math.max(maxArea, heights[tp] * width);
                i--;
            }
        }
        return maxArea;
    }
}

/*
   单调栈(Monotone Stack)
    - 单调栈首先是栈,是栈的应用
    - 栈内元素维持了"单调性"的应用场景
      1. 单调递增(不减)栈可以找到左边第一个比当前出栈元素小(包含等于)的元素
      2. 单调递减(不增)栈可以找到左边第一个比当前出栈元素大(包含等于)的元素

   练习:
    42
    739
    496
    316
    901
    402
    581
  */

3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)

标签:right,cur,int,复杂度,heights,height,0084,Histogram,LeetCode
来源: https://www.cnblogs.com/junstat/p/16197464.html