Largest Rectangle in Histogram

来源:互联网 发布:招商银行java面试 编辑:程序博客网 时间:2024/06/07 14:13

Largest Rectangle in Histogram

标签(空格分隔): leetcode, 算法,堆栈


1. 题目

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.

2. 解答

解法一:暴力法

对柱状图的每一项,向前向后比较找出它能行程的面积最大的矩形。

class Solution {public:    int largestRectangleArea(vector<int>& heights) {        if (heights.empty()) {            return 0;        }        int maxArea = heights[0];        for (int i = 0; i < heights.size(); ++i) {            int area = heights[i];  //柱状图中的每一项能形成的最大面积            for (int j = i + 1; j < heights.size(); ++j) {                if (heights[j] >= heights[i]) {                    area += heights[i];                } else {                    break;                }            }            for (int k = i - 1; k >= 0; --k) {                if (heights[k] >= heights[i]) {                    area += heights[i];                } else {                    break;                }            }            if (area > maxArea) {                maxArea = area;            }        }        return maxArea;    }};

然而由于超时无法通过o(n^2)。

解法二:利用栈

利用栈构造非递减序列, 参考博客。

class Solution {public:    int largestRectangleArea(vector<int>& heights) {        int maxArea = 0;        stack<int> s;        for (vector<int>::size_type i = 0; i < heights.size(); ++i) {           if (s.empty() || s.top() <= heights[i]) {               s.push(heights[i]);           } else {               int popCnt = 0;               while (!s.empty() && s.top() > heights[i]) {                   maxArea = max(maxArea, s.top() * (popCnt + 1));                   s.pop();                   ++popCnt;               }               while(popCnt) {                   s.push(heights[i]);                   --popCnt;               }               s.push(heights[i]);           }       }       int popCnt = 0;       while (!s.empty()) {           maxArea = max(maxArea, s.top() * (popCnt + 1));           s.pop();           ++popCnt;       }       return maxArea;    }};
原创粉丝点击