标签:style blog http color io ar strong for div
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.
解题分析:
申请一个辅助栈,stack里面只存放单调递增的索引
class Solution { public: int largestRectangleArea(vector<int> &height) { if (height.size() == 0) return 0; height.push_back(0); // 便于最后计算所有的矩形面积 std::stack<int> stk; // 存放的是数组索引下标 int result = 0; for (int i = 0; i < height.size(); ) { if (stk.empty() || height.at(i) > height.at(stk.top())) { stk.push(i); ++i; } else { int idx = stk.top(); stk.pop(); int area = height.at(idx) * (stk.empty() ? i : i - stk.top() - 1); result = std::max(result, area); } } return result; } };
时间复杂度T(n) = O(n)
Leetcode:Largest Rectangle in Histogram 最大矩形面积
标签:style blog http color io ar strong for div
原文地址:http://www.cnblogs.com/wwwjieo0/p/3967183.html