84. 柱状图中最大的矩形

不念不忘少年蓝@ 2023-02-08 12:41 33阅读 0赞

题目:https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
目的:找到面积最大的矩形
面积 = 高度 * 宽度
高度确定,宽度不确定
1 暴力穷举法
思路:双指针。
1.1 左指针向左移动,直到第一个比自己矮的矩形
1.2 右指针向右移动,直到第一个比自己矮的矩形

  1. class Solution {
  2. public int largestRectangleArea(int[] heights) {
  3. int len = heights.length;
  4. int[] arr = new int[len+2];
  5. for (int i = 0; i< heights.length; i++) {
  6. arr[i+1] = heights[i];
  7. }
  8. int ans = 0;
  9. for (int i = 1; i < arr.length-1; i++) {
  10. int currentHeight = arr[i];
  11. int left = i;
  12. int right = i;
  13. while (left > 0 && arr[left] >= arr[i] ) {
  14. left--;
  15. }
  16. while (right < arr.length-1 && arr[right] >= arr[i]) {
  17. right++;
  18. }
  19. ans = Math.max(ans, currentHeight * (right - left-1));
  20. }
  21. return ans;
  22. }
  23. }

2 单调栈
定义一个栈,指针向右移动,比自己高就入栈,直到遇到比自己低的矩形,不入栈,而是出栈,一直出到比自己矮的矩形

  1. class Solution {
  2. public int largestRectangleArea(int[] heights) {
  3. // 单调栈 https://leetcode-cn.com/problems/largest-rectangle-in-histogram/solution/java-shuang-jie-fa-dai-ma-jian-ji-yi-dong-dan-diao/
  4. int len = heights.length;
  5. int[] arr = new int[len+2];
  6. for (int i = 0; i< len; i++) {
  7. arr[i+1] = heights[i];
  8. }
  9. // heights [2, 1, 5, 6, 2, 3]
  10. // arr [0, 2, 1, 5, 6, 2, 3, 0]
  11. int res = 0;
  12. int index = 1;
  13. Deque<Integer> stack = new ArrayDeque<>();
  14. stack.push(0);
  15. while (index < arr.length) {
  16. while (index < arr.length && arr[index] >= arr[stack.peek()]) {
  17. stack.push(index);
  18. index++;
  19. }
  20. while (index < arr.length && arr[index] < arr[stack.peek()]) {
  21. int curHeight = arr[stack.pop()];
  22. res = Math.max(res, curHeight * (index - stack.peek() - 1));
  23. }
  24. }
  25. return res;
  26. }
  27. }

推荐题解: https://leetcode-cn.com/problems/largest-rectangle-in-histogram/solution/java-shuang-jie-fa-dai-ma-jian-ji-yi-dong-dan-diao/

发表评论

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

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

相关阅读