LeetCode系列84—柱状图中最大的矩形

题意

84. 柱状图中最大的矩形

题解

方法一:暴力方法

枚举宽度或者高度

方法二:单调栈

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

public class Solution {
    
    

    public int largestRectangleArea(int[] heights) {
    
    
        int len = heights.length;
        if (len == 0) {
    
    
            return 0;
        }
        if (len == 1) {
    
    
            return heights[0];
        }

        int area = 0;
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < len; i++) {
    
    
            while (!stack.isEmpty() && heights[stack.peekLast()] > heights[i]){
    
    
                int height = heights[stack.removeLast()];

                while (!stack.isEmpty() &&  heights[stack.peekLast()] == height){
    
    
                    stack.removeLast();
                }

                int width;
                if (stack.isEmpty()){
    
    
                    width = i;
                } else {
    
    
                    width = i - stack.peekLast() - 1;
                }

                area = Math.max(area , width * height);
            }
            stack.addLast(i);
        }

        while (!stack.isEmpty()){
    
    
            int height = heights[stack.removeLast()];

            while (!stack.isEmpty() &&  heights[stack.peekLast()] == height){
    
    
                stack.removeLast();
            }

            int width;
            if (stack.isEmpty()){
    
    
                width = len;
            } else {
    
    
                width = len - stack.peekLast() - 1;
            }

            area = Math.max(area , width * height);
        }
        return area;
    }
}

方法三:单调栈+哨兵

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

public class Solution {
    
    

    public int largestRectangleArea(int[] heights) {
    
    
        int len = heights.length;
        if (len == 0) {
    
    
            return 0;
        }
        if (len == 1) {
    
    
            return heights[0];
        }

        int area = 0;
        int[] newHeights = new int[len + 2];
        for (int i = 0; i < len; i++) {
    
    
            newHeights[i + 1] = heights[i];
        }
        len += 2;
        heights = newHeights;

        Deque<Integer> stack = new ArrayDeque<>();
        stack.addLast(0);

        for (int i = 1; i < len; i++) {
    
    
            while (heights[stack.peekLast()] > heights[i]) {
    
    
                int height = heights[stack.removeLast()];
                int width  = i - stack.peekLast() - 1;
                area = Math.max(area, width * height);
            }
            stack.addLast(i);
        }
        return area;
    }
}

参考

柱状图中最大的矩形

猜你喜欢

转载自blog.csdn.net/younothings/article/details/120135762
今日推荐