leetcode84. Largest Rectangle in Histogram

来源:互联网 发布:java jsoup爬虫技术 编辑:程序博客网 时间:2024/05/16 03:01

84. Largest Rectangle in Histogram

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.

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given heights = [2,1,5,6,2,3],
return 10.

解法

利用栈,找左边第一个小于的数和右边第一个小于的数,如果栈只剩最后一个元素,该面积为i*height;如果大于1个元素,面积为(i-stack.peek - 1 ) * height。

public class Solution {    public int largestRectangleArea(int[] heights) {         if (heights == null || heights.length == 0) {            return 0;        }        Stack<Integer> stack = new Stack<Integer>();        int max = 0;        for (int i = 0; i <= heights.length; i++) {            int curHeight = i == heights.length ? 0 : heights[i];            while (!stack.empty() && curHeight <= heights[stack.peek()]) {                int height = heights[stack.pop()];                int width = stack.empty() ? i : i - stack.peek() - 1;                max = Math.max(max, height * width);            }            stack.push(i);        }        return max;    }}

这里写图片描述

1 0
原创粉丝点击