LeetCode 84. Largest Rectangle in Histogram
解法一:Monotone Stack
用栈来解决本问题是一种很巧妙的解法,主要运用单调栈。由于面积受制于高度较低的矩形,因此由高至低来处理(最高的宽度为1,其相邻的次高的宽度可以用到最高的,为2,以此类推)。所以本题采用递增的栈,遇到小的元素就pop直至栈顶元素<=当前元素,对于pop出来的元素(一定是由高到低的顺序)依次进行处理。
对于宽度的处理,我们可以将元素的下标存到栈里,利用下标进行宽度的计算:i-stack[top-1]-1 。(一开始我是 i-stack[top]来做,但是如果前面的元素不在stack里就不对了,如[1,3,2,5] 中3 pop了)。需要注意的是,遇到很小的元素,或者最后的时候,导致栈内所有元素都要出栈时,最后一个出栈的元素将会是迄今最小的元素,这里计算面积的时候,高就是这个元素,但宽则变成了i,需要特别注意。
class Solution { public: int largestRectangleArea(vector<int>& heights) { heights.push_back(0); stack<int> s; //index stack int res=0; for (int i=0;i<heights.size();++i){ while (!s.empty() && heights[i]<heights[s.top()]){ int h=heights[s.top()]; s.pop(); int x=s.empty()?-1:s.top(); //if stack is empty, x will be i res = max(res, h*(i-x-1)); } s.push(i); } return res; } };
关于单调栈,可以参考 http://www.cnblogs.com/grandyang/p/8887985.html
解法二: Divide and Conquer
找到最小的元素,分别寻找左侧和右侧的最大矩形面积。最大的矩形也可能经过最小的元素,这种情况下,面积 = 最小元素*(high-low+1)(最大面积受制于最小的高)。时间复杂度为O(nlogn)。
class Solution { public: int calArea(vector<int> &heights, int low, int high){ if (low>high) return 0; int minIndex=low; for (int i=low;i<=high;++i) if (heights[i]<heights[minIndex]) minIndex = i; return max(heights[minIndex]*(high-low+1), max(calArea(heights,low,minIndex-1), calArea(heights,minIndex+1,high))); } int largestRectangleArea(vector<int>& heights) { return calArea(heights,0,heights.size()-1); } };
上述代码还是无法AC,这是由于如果输入是有序的,时间复杂度会变为O(n^2)。解决方法是使用线段树来优化,详见 https://leetcode.com/problems/largest-rectangle-in-histogram/solution/。