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
.
思路: 注意一点: 只要计算出以每个柱形为最小值的矩形面积即可。使用一个栈,栈内始终保存一个递增序列的 index,若是 新的柱形长度小于栈顶元素,则退出栈顶直到栈内元素的长度不大于新的柱形的长度为止,并且,对于每一个退栈元素,计算以其长度为最小值的面积。(宽的左边为其自身位置,右边为新到元素的位置)时间:O(n)
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int n = height.size(), max_area = 0;
int Id, area;
int i = 0;
stack<int> st; // save the index
while(i < n) {
if(st.empty() || height[i] >= height[st.top()]) st.push(i++);
else {
Id = st.top();
st.pop();
area = height[Id] * (st.empty() ? i : i - st.top() - 1);
if(area > max_area) max_area = area;
}
}
while(!st.empty()) {
Id = st.top();
st.pop();
area = height[Id] * (st.empty() ? i : i - st.top() - 1);
if(area > max_area) max_area = area;
}
return max_area;
}
};
Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
思路: 一行一行的记录下当前高度, 用上题的思路计算一下,即可。时间: O(n)
int getMaxArea(vector<int> &h) {
stack<int> st;
int maxArea, i = 0;
while(i < h.size()) {
if(st.empty() || h[st.top()] <= h[i]) { st.push(i++); continue; }
while(!st.empty() && h[st.top()] > h[i]) {
int id = st.top();
st.pop();
int area = h[id] * (st.empty() ? i : i - st.top() - 1);
if(area > maxArea) maxArea = area;
}
}
while(!st.empty()) {
int id = st.top();
st.pop();
int area = h[id] * (st.empty() ? i : i - st.top() - 1);
if(area > maxArea) maxArea = area;
}
return maxArea;
}
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if(matrix.size() == 0 || matrix[0].size() == 0) return 0;
int row = matrix.size(), col = matrix[0].size();
vector<int> h(row, 0);
int maxArea = 0;
for(int c = 0; c < col; ++c) {
for(int r = 0; r < row; ++r) {
if(matrix[r][c] == '1') ++h[r];
else h[r] = 0;
}
maxArea = max(maxArea, getMaxArea);
}
return maxArea;
}
};