lintcode: Largest Rectangle in Histogram
2016-04-18 22:14
369 查看
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.
对于每个bar,找出bar是最矮的范围,求出一个面积;遍历所有bar,得到max面积。
超时
/article/5789867.html
方法一
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
用递增栈/article/5789867.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; } };
相关文章推荐
- Pentaho Work with Big Data(八)—— kettle集群
- 模拟链表
- 替换位置
- Coinbase在美国推出借记卡兑换比特…
- 拥有1900万客户的日本娱乐巨头DMM…
- 为什么中国防火墙会给比特币矿工造…
- 香港财长提及“区块链”背后的重大意…
- 从风险管理角度看比特币扩容决策
- 俄罗斯比特币用户世界第五 央…
- Bitwage与保险公司合作 提供…
- mysql常用指令
- G20峰会:FSB将区块链和互联网金融…
- BitFury集团宣布对BitPesa公司进行…
- 韩国证券交易所开发区块链交易体系
- IBM高管当选为区块链项目委员会主…
- 韩国证券交易所开发区块链交易体系
- IBM高管当选为区块链项目委员会主…
- 红杉资本:区块链技术或对万事达的…
- windows软件:Adobe Acrobat Ⅺ Pro激活教程
- 比特币不能颠覆世界,但它的区块链…