问题描述
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
.
问题十分简单
几个比较常见的思路
-
朴素的想法:
从每一个位置分别向左右两个方向进行查找,直到第一个比该位置高度低的位置为止。
不妨计所在位置为x,左端位置为i, 右端位置为j ,则该位置对应的矩形高度就是:(j - i - 1) * height[x]。
这个朴素的方法由于大量重复的查找,其复杂度为O(n^2),无法AC;
-
助教给的思路:
用栈来解决这个问题,思路如下:
先向给定向量push一个0用于最后出栈 不断向前遍历元素,记当前访问的元素为x 如果栈为空或者栈顶元素k比x高度要低,则将x进栈; 如果x比栈顶元素要低,出栈栈顶元素k,记k出栈后栈顶元素为 prev(k) 则k位置对应的矩形面积将为:(x - prev(k) - 1) * height[k]; 重复上述操作直到当前栈顶元素比当前元素x要大为止,然后将x进栈 重复该过程直到遍历结束
由于每个元素只需进出栈一次,该算法复杂度为O(n)
代码:
int largestRectangleArea2(vector<int>& height) { height.push_back(0); const int size = height.size(); stack<int> temp; int i = 0, res = 0; while (i < size) { if (temp.empty() || height[i] >= height[temp.top()]) temp.push(i++); else { int h = temp.top(); temp.pop(); res = max(res, height[h] * (temp.empty() ? i : i - temp.top() - 1)); } } return res; }
因为一开始想到了别的解法,
我没有使用这种思路。
-
动态规划\贪心?
我使用了(动态规划\贪心?)的思路:
核心问题在于寻找左右两端比当前位置高度要低且距离当前位置最远的一个区间。
那么我们为何不能通过调用之前位置记录的区间极限来加快搜索呢?
具体思路类似KMP,通过两个数组来记录比当前位置高度低的最左最右两个元素,把朴素思想中的移位操作改为访问对应位置的最左或最右区间端点,借此节省查找,结果还算可以:
16ms AC beats 93.87%
代码:
int largestRectangleArea(vector<int>& height) { int size = height.size(); int *left = new int[size + 2]; int *right = new int[size + 2]; int ans = 0; int temp; left[0] = 0; right[size + 1] = 0; for (int i = 1, k = 0; i <= size;) { if (k == 0 || height[k - 1] < height[i - 1]) { left[i] = k; i++; k = i - 1; } else { k = left[k]; } } for (int i = size, k = size + 1; i >= 1;) { if (k == size + 1 || height[k - 1] < height[i - 1]) { right[i] = k; i--; k = i + 1; } else { k = right[k]; } } for (int i = 1; i <= size; i ++) { temp = (-left[i] + right[i] - 1) * height[i - 1]; if (temp > ans) { ans = temp; } } return ans; }
关联问题
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.
思路十分相似:数据DP预处理后按行做上述解法即可