leetcode 084 —— Largest Rectangle in Histogram

来源:互联网 发布:淘宝店铺封了怎么激活 编辑:程序博客网 时间:2024/06/05 01:15

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.


思路:此题最容易想到的是中间往两边扫描,但是这种方法时间是 O(n2),看到提示是栈,那么就用栈存储递增序列,如果出现降序,则计算最大值,然后将适量的栈顶元素入栈,继续往后扫描。虽然时间是O(n),但是在网上找到了新的方法,只将栈顶元素的下标入栈。不得不服。链接在这里

我的拙劣代码

class Solution {public:int largestRectangleArea(vector<int>& height) {int n = height.size();int i = 0;int maxS = 0;stack<int> stk;while (i < n){stk.push(height[i]);while (i + 1 < n&&height[i + 1] >= height[i]){ //  存放递增序列stk.push(height[++i]);}if (i + 1 == n){ //末端为递增序列int len = 1;while (!stk.empty()){maxS = max(maxS, stk.top()*len);stk.pop();len++;}break;}else{  //i+1为小于栈顶的数int len = 1;while (!stk.empty()&&height[i + 1] < stk.top()){maxS = max(maxS, stk.top()*(len));stk.pop();len++;}while (len - 1){stk.push(height[i + 1]);len--;}i++;}}return maxS;}};


网上的代码

class Solution {public:int Max(int a, int b){ return a > b ? a : b; }int largestRectangleArea(vector<int> &height) {height.push_back(0);stack<int> stk;int i = 0;int maxArea = 0;while (i < height.size()){if (stk.empty() || height[stk.top()] <= height[i]){  //递增序列则入栈stk.push(i++);}else {int t = stk.top();stk.pop();maxArea = Max(maxArea, height[t] * (stk.empty() ? i : i - stk.top() - 1));}}return maxArea;}};




0 0
原创粉丝点击