Leetcode Largest Rectangle in Histogram

来源:互联网 发布:dede模板下载站源码 编辑:程序博客网 时间:2024/06/03 21:41

Leetcode Largest Rectangle in Histogram,使用栈来解决本题,栈的元素有两个域,即:first(对应的值),second(对应的个数)。在使用栈时,我们考虑到三种情况,记当前要处理的元素为cur,注:以下算法,在弹出栈中元素时都计算面积(cur.first * cur.second),并与当前最大值比较,留下较大者。

  1. 如果栈空,则直接push此元素入栈,个数为1
  2. 如果cur大于栈顶元素,直接push此元素入栈,个数为1
  3. 如果cur小于栈顶元素,弹出顶部元素,记此元素为old_top,弹出之后的
    1. 如果新的栈顶元素大于cur,则把old_top元素记数累记到新的栈顶元素上。
    2. 如果新的栈顶元素小于cur,则把old_top元素记数累加到cur上


在经过以上处理后,对于栈中遗留元素,直接进行个顶至下累计,直到栈被弹空。
代码如下:
#include<iostream>#include<vector>#include<stack>using namespace std;class Solution {public:    int largestRectangleArea(vector<int>& heights) {        int max = 0;        stack<pair<int, int>> current;        pair<int, int> top;        int tmp;        for (int i = 0; i < heights.size(); i ++) {            if (current.empty()) {                current.push(make_pair(heights[i], 1));            } else {                if (heights[i] > current.top().first) {                    current.push(make_pair(heights[i], 1));                } else {                    pair<int, int> cur_pair = make_pair(heights[i], 1);                    while (!current.empty() && heights[i] < current.top().first) {                        top = current.top();                        current.pop();                        // if the current top is higher than heights[i],                        // accumulate the number of removed count to it.                        if (!current.empty() && current.top().first > cur_pair.first) {                            current.top().second += top.second;                        } else {                            cur_pair.second += top.second;                        }                        // calculate the current max                        tmp = top.first * top.second;                        if (tmp > max) {                            max = tmp;                        }                    }                    current.push(cur_pair);                }            }        }        int count = 0;        // calculate the rest        while (!current.empty()) {            top = current.top();            current.pop();            tmp = top.first * (top.second + count);            if (tmp > max) {                max = tmp;            }            count += top.second;        }        return max;    }};// Sample input: ./a.out num1 num2 num3...int main(int argc, char * argv[]) {    Solution so;    vector<int> test;    for (int i = 1; i < argc; i ++) {        test.push_back(atoi(argv[i]));    }    int re = so.largestRectangleArea(test);    cout<<"re: "<<re<<endl;    return 0;}
测试:./a.out 2 1 5 6 2 3结果:re: 10
0 0
原创粉丝点击