problem:
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
.
Hide Tags
题意:在一个数组表示的柱状图中寻找最大的矩形面积
thinking:
(1)最先想到暴力破解,两次遍历,记录最大面积。提交发现超时了。
(2)http://blog.csdn.net/doc_sgl/article/details/11805519 给出了一个用stack实现的O(n)算法,很高效。
大致思想是:stack里面只存放height单调递增的索引,最大矩形最可能出现在这几列中
code:
暴力破解: 提交 TLE
class Solution { public: int largestRectangleArea(vector<int> &height) { int n=height.size(); if(n==0) return 0; if(n<2) return height[0]; int area=height[0]; int index=0; for(int i=1;i<n;i++) { index=height[i]; for(int j=i;j>=0;j--) { index=min(index,height[j]); area=max(area,index*(i-j+1)); } } return area; } };
借助stack O(N)算法
class Solution { public: int Max(int a, int b){return a > b ? a : b;} int largestRectangleArea(vector<int> &height) { height.push_back(0); stack<int> stk; int i = 0; int maxArea = 0; while(i < height.size()){ if(stk.empty() || height[stk.top()] <= height[i]){ stk.push(i++); }else { int t = stk.top(); stk.pop(); maxArea = Max(maxArea, height[t] * (stk.empty() ? i : i - stk.top() - 1)); } } return maxArea; } };
时间: 2024-10-23 14:24:03