LeetCode Largest Rectangle in Histogram

来源:互联网 发布:大数据产业园规划 编辑:程序博客网 时间:2024/05/22 08:38

原题链接在这里:https://leetcode.com/problems/largest-rectangle-in-histogram/

参考了这篇帖子:http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html

里面讲的很清楚,生成了stack, 当遇到比stack 顶部更大array元素时或者stack为空时,就把更打元素的index存入stack中。

当遇到小元素时,要出栈并更新maxArea.

Note: 1. 需新生成一个array, 长度为原array 长度+1,用Arrays.copyOf()来复制原array, 并把最后一个数字设为0.

2. 数组里存的是index, 而不是array的元素。

AC Java:

public class Solution {    public int largestRectangleArea(int[] height) {        if(height == null || height.length == 0){            return 0;        }        Stack<Integer> stk = new Stack<Integer>();        int [] h = new int[height.length + 1];        h = Arrays.copyOf(height,height.length+1);        int i = 0;        int maxArea = 0;        while(i<h.length){            if(stk.isEmpty() || h[stk.peek()] <= h[i]){                stk.push(i);                i++;            }else{                int index = stk.pop();                maxArea = Math.max(maxArea, h[index] * (stk.isEmpty() ? i : i-stk.peek()-1));            }        }        return maxArea;    }}


0 0