首页 > 其他 > 详细

[LeetCode]Largest Rectangle in Histogram

时间:2015-11-22 17:16:43      阅读:233      评论:0      收藏:0      [点我收藏+]

题目解析:(链接)

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.

 

Subscribe to see which companies asked this question

解题思路:

O(n^2)的代码很好写,下面是copy来的O(n)的解题思路:

原帖地址:http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int>& height) {
 4         stack<int> cache;
 5         int result = 0;
 6         height.push_back(0);
 7         for (int i = 0; i < height.size(); ) {
 8             if (cache.empty() || height[i] >= height[cache.top()]) {
 9                 cache.push(i++);
10             } else {
11                 int index = cache.top();
12                 cache.pop();
13                 int muliply = cache.empty()? i : i - cache.top() - 1;
14                 result = max(result, height[index] * muliply);
15             }
16         }
17         
18         return result;
19     }
20 };

 

[LeetCode]Largest Rectangle in Histogram

原文:http://www.cnblogs.com/skycore/p/4986071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!