Largest Rectangle in Histogram
来源:互联网 发布:招商银行java面试 编辑:程序博客网 时间:2024/06/07 14:13
Largest Rectangle in Histogram
标签(空格分隔): leetcode, 算法,堆栈
1. 题目
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 heights = [2,1,5,6,2,3],
return 10.
2. 解答
解法一:暴力法
对柱状图的每一项,向前向后比较找出它能行程的面积最大的矩形。
class Solution {public: int largestRectangleArea(vector<int>& heights) { if (heights.empty()) { return 0; } int maxArea = heights[0]; for (int i = 0; i < heights.size(); ++i) { int area = heights[i]; //柱状图中的每一项能形成的最大面积 for (int j = i + 1; j < heights.size(); ++j) { if (heights[j] >= heights[i]) { area += heights[i]; } else { break; } } for (int k = i - 1; k >= 0; --k) { if (heights[k] >= heights[i]) { area += heights[i]; } else { break; } } if (area > maxArea) { maxArea = area; } } return maxArea; }};
然而由于超时无法通过o(n^2)。
解法二:利用栈
利用栈构造非递减序列, 参考博客。
class Solution {public: int largestRectangleArea(vector<int>& heights) { int maxArea = 0; stack<int> s; for (vector<int>::size_type i = 0; i < heights.size(); ++i) { if (s.empty() || s.top() <= heights[i]) { s.push(heights[i]); } else { int popCnt = 0; while (!s.empty() && s.top() > heights[i]) { maxArea = max(maxArea, s.top() * (popCnt + 1)); s.pop(); ++popCnt; } while(popCnt) { s.push(heights[i]); --popCnt; } s.push(heights[i]); } } int popCnt = 0; while (!s.empty()) { maxArea = max(maxArea, s.top() * (popCnt + 1)); s.pop(); ++popCnt; } return maxArea; }};
阅读全文
0 0
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- html5调用手机相机并压缩、上传
- android gps机制分析--之三
- 女装大佬
- 1142: 简单的事情
- css 布局中的 BFC
- Largest Rectangle in Histogram
- LeetCode 338. Counting Bits
- Android开发常见问题之"Failed to convert @drawable/xx into a drawable Exception details are logged in Window
- ImageLoader+网络请求+ListView多条目加载
- java版本升级异常Unsupported major.minor version 52.0处理
- 常见html错误
- iOS 使用AVPlayer自定义的播放器,当手机在静音模式播放器也静音的解决方法!
- CDH(hadoop) install on ubuntu 14.04server
- 泛型基础----------泛型方法二