码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:Largest Rectangle in Histogram 最大矩形面积

时间:2014-09-11 20:52:42      阅读:323      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   strong   for   div   

Largest Rectangle in Histogram

Given n non-negative integers representing the histograms bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

bubuko.com,布布扣

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

bubuko.com,布布扣

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

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

 

解题分析:

园友博文分析

申请一个辅助栈,stack里面只存放单调递增的索引

bubuko.com,布布扣

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        if (height.size() == 0) return 0;
        height.push_back(0);   // 便于最后计算所有的矩形面积
        std::stack<int> stk;   // 存放的是数组索引下标
        int  result = 0;
        for (int i = 0; i < height.size(); ) {
            if (stk.empty() || height.at(i) > height.at(stk.top())) {
                stk.push(i);
                ++i;
            } else {
                int idx = stk.top();
                stk.pop();
                int area = height.at(idx) * (stk.empty() ? i : i - stk.top() - 1);
                result = std::max(result, area);
            }
        }
        return result;
    }
};

 时间复杂度T(n) = O(n)

Leetcode:Largest Rectangle in Histogram 最大矩形面积

标签:style   blog   http   color   io   ar   strong   for   div   

原文地址:http://www.cnblogs.com/wwwjieo0/p/3967183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!