zoukankan      html  css  js  c++  java
  • [LeetCode]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.

    思考:记录每个矩形最左最右比自己高的矩形下标,左右相减即为长,乘以矩形高,即为当前矩形可以组成矩形最大面积。求最大值。

    struct Node{
    	int height;
    	int left;
    	int right;
    	int area;
    };
    class Solution {
    public:
        int largestRectangleArea(vector<int> &height) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		
    		int i;
    		int maxarea=0;
    		int len=height.size();
    		Node *h=new Node[len+2];
    		for(i=1;i<=len;i++)
    		{
    			h[i].height=height[i-1];
    			h[i].left=i;
    			h[i].right=i;
    		}
    	
    		h[0].height=-1;
    		h[len+1].height=-1;
    		for(i=1;i<=len;i++)
    		{
    			while(h[i].height<=h[h[i].left-1].height)
    				h[i].left=h[h[i].left-1].left;
    		}
    	
    		for(i=len;i>=1;i--)
    		{
    			while(h[i].height<=h[h[i].right+1].height)
    				h[i].right=h[h[i].right+1].right;
    		}
    		for(i=1;i<=len;i++)
    		{
    			h[i].area=h[i].height*(h[i].right-h[i].left+1);
    			if(maxarea<h[i].area)
    				maxarea=h[i].area;
    		}
    
    		delete []h;
    		return maxarea;
    	}
    };
    

      

  • 相关阅读:
    pdf-2-eps
    使用terminator
    自动删除源文件中的指定行--sed
    apt-get update只是更新源列表?
    LoadRunner学习
    计算一个人从出生到目前一共生活了多少天
    数组的求交集和并集
    获取北京和张北的天气
    重新梳理java入门
    java 基础
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3429482.html
Copyright © 2011-2022 走看看