**Leetcode_largest-rectangle-in-histogram(c++ and python version)

62 篇文章 0 订阅
52 篇文章 0 订阅

地址:http://oj.leetcode.com/problems/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 height = [2,1,5,6,2,3],
return 10.

思路:找到一个height[k],其比height[k+1]小,循环统计height[0]到height[K]之间的最大面积。因为若height[i]比height[i+1]小的话,最大面积的边肯定不是height[i]

参考代码:

class Solution:
    # @param height, a list of integer
    # @return an integer
    def largestRectangleArea(self, height):
        if not height: return 0
        elif len(height)==1:return height[0]
        i = 0
        ans = 0
        flag = False
        while i < len(height) and not flag:
            while i<len(height)-1 and height[i] <= height[i+1]:
                i += 1
            if i == len(height)-1:
                flag = True
            min_height = height[i]
            for j in range(i, -1, -1):
                min_height = min(min_height, height[j])
                ans = max(ans, min_height*(i-j+1))
            i+=1
        return ans
        


思路:

上面python用的是分治法,可以ac,但是c++可能时间卡的比较严格,会tle

用stack来解,如果栈为空或者当前读入的数值不小于栈顶的值,将该值入栈,并读入下一个值。

否则(当前读入的值小于栈顶最小值),把小于当前值的栈内所有值都pop出来,并算出此时面积。

算面积时考虑两种情况,一个是栈已空,一个是栈非空。

如此,直到遍历完(读入)所有值。

若此时栈非空,栈里的数值一定是非降序的,同样考虑栈空和非空两种情况,算出面积。

最后的结果是上述面积值的最大值。

参考代码:

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        if(height.empty())
            return 0;
        stack<int>st;
        int pos, ans = 0;
        for(int i = 0; i<height.size(); ++i) {
            while(!st.empty() && height[i] < height[st.top()]) {
                pos = st.top();
                st.pop();
                ans = max(ans, height[pos] * (st.empty() ? i : i-st.top()-1));
            }
            st.push(i);
        }
        while(!st.empty()){
            pos = st.top();
            st.pop();
            ans = max(ans, height[pos] * (int)(st.empty() ? height.size() : height.size()-1-st.top()));
        }
        return ans;
    }
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值