【LeetCode】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.

提示:

这道题最直接的方法就是暴力搜索了,从第一个方块开始,向前向后一直搜索到比它高度小的方块为止,然后更新最大面积,这种方法的时间复杂度是O(n^2)。

有没有更好的方法呢?答案是有的。借助于stack这一数据结构,可以实现一个O(n)的算法,具体思路如下。

stack中存储的是方块的下标索引号,如果当前方块的高度大于等于栈顶元素对应方块的高度,那么就将该方块的索引号进栈。

否则(即当前方块高度更小时),则说明继续划分下去会产生镂空区域,因此我们将栈顶元素一次出栈,每次出栈时都计算一下以该栈顶元素为高度基准时,划分出的面积大小。

这样这个算法复杂度就降低到了O(n),具体请看代码。

代码:

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        if (heights.size() == 0) {
            return 0;
        }
        stack<int> index;
        int res = 0, i = 0;
        while (i < heights.size()) {
            if (index.empty() || heights[index.top()] <= heights[i]) {
                index.push(i++);
            } else {
                int top = heights[index.top()];
                index.pop();
                int size = top * (index.empty() ? i : i - index.top() - 1);
                res = max(res, size);
            }
        }
        while (index.size()) {
            int top = heights[index.top()];
            index.pop();
            int size = top * (index.empty() ? i : i - index.top() - 1);
            res = max(res, size);
        }
        return res;
        
    }
};
原文地址:https://www.cnblogs.com/jdneo/p/5367904.html