84. Largest Rectangle in Histogram

来源:互联网 发布:人有多复杂知乎 编辑:程序博客网 时间:2024/05/22 05:52

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.

题意是找出给出的直方图中最大的矩形面积。其实是在处理一个递增的栈,例如5 6这三个直方图,那么它的最大面积有两种情况:5*2=10;6*1=6三种情况。所以在5 6这三个直方图中,一旦遇到小于栈顶的直方图,则可以进行这样的面积计算的操作。例如遇到了2,所以此时栈顶元素是6,那么就计算6*1,接下来弹出,那当前栈顶元素是5,所以计算5*2。诸如此类。为什么要是递增才可以?因为递增的话,栈中每个元素都能乘以当前值乘以栈的大小。

假设处理完6之后,遇到了一个4,这是会先计算5*2 (因为5>4),然后再判断4和栈顶的1,此时4>1,那么就会插入栈顶,这时候下一个遇到比4小的话,那么就会计算4*3=12。所以其实这个栈维护的是一个矩形的底一样的长度。因为4会比5和6小(前几部有了判断),所以4*3是正确的。代码如下:时间复杂度为O(n),空间复杂度为O(n)


Code:(LeetCode运行12ms)

class Solution {public:    int largestRectangleArea(vector<int>& heights) {        stack<int> Stack;        //最后入栈一次0,如上图中最后一直递增,最后不会处理,插入0后则会进行处理        heights.push_back(0);        int result = 0;        for (int i = 0; i < heights.size(); ) {            if (Stack.empty() || heights[i] > heights[Stack.top()]) {                Stack.push(i++);            } else {                int temp = Stack.top();                Stack.pop();                result = max(result, heights[temp] * (Stack.empty() ? i : i - Stack.top() - 1));            }        }        return result;    }};



原创粉丝点击