lintcode: 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.

方法一

O(n^2)
对于每个bar,找出bar是最矮的范围,求出一个面积;遍历所有bar,得到max面积。
超时

class Solution {
public:
    /**
     * @param height: A list of integer
     * @return: The area of largest rectangle in the histogram
     */
    int largestRectangleArea(vector<int> &height) {
        // write your code here

        int maxArea=0;

        for(int i=0;i<height.size();i++){

            int left;
            if(i==0){
                left=i;
            }else{
                left=i-1;
                while(left>=0 && height[left]>=height[i]) left--;
                left++;
            }

            int right;
            if(i==height.size()-1){
                right=i;
            }else{
                right=i+1;
                while(right<=height.size()-1 && height[right]>=height[i]) right++;
                right--;
            }

            int area=(right-left+1)*height[i];

            if(area>maxArea){
                maxArea=area;
            }

        }

        return maxArea;
    }
};

方法2

用递增栈
http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html

class Solution {
public:
    /**
     * @param height: A list of integer
     * @return: The area of largest rectangle in the histogram
     */
    int largestRectangleArea(vector<int> &height) {
        // write your code here

        stack<int> stk;

        int maxArea=0;

        int i=0;

        vector<int> h(height);
        //后面加个0
        h.push_back(0);

        while(i<h.size()){
            if(stk.empty() || h[i]>=h[stk.top()]){
                stk.push(i);
                i++;
            }else{
                int t=stk.top();
                stk.pop();

                int area=h[t]*(stk.empty()?i:(i-stk.top()-1));
                if(area>maxArea){
                    maxArea=area;
                }
            }
        }

        return maxArea;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值