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.
分析:
看到首先想到的是,遍历每一个元素height[index], 再从index向左右遍历,寻找以height[index]为高度的最大矩形。
这是我的代码:
public class Solution { public int largestRectangleArea(int[] height) { int area = 0; for(int index=0; index<height.length; index++){ //剪枝,剪去重复元素 if(index != height.length-1 && height[index+1]==height[index]) index++; int i = index, j=index; while(i>=0 && height[i]>=height[index]) i--; while(j<height.length && height[j]>=height[index]) j++; int width = j-i-1; area = Math.max(area, height[index]*width); } return area; } }
时间复杂度是O(n^2),即使我剪去了重复元素,最后还是TLE了,可见,上面不是leetcode想要的结果。
接下来的思路就是我在网上看别人的了。
利用一个栈,栈里保存的是下标,而且栈里保存的是递增元素的下标,
从前往后遍历,
如果栈为空或者遇见比栈顶元素大,则把下标入栈,
如果当前元素比栈顶元素小,则弹栈,直到栈为空或者栈顶元素比当前元素小,
每弹一次栈,都要计算一次矩形面积,因为栈里维持的元素是递增的,则可以保证刚弹出的元素end和当前遍历到元素i之间的值都比height[end]大,所以都可以加入计算矩形的宽,高度则为当前弹出的元素,
直到最后一个元素,如果栈还不是空的,则应该继续弹栈,直到栈空。
public class Solution { public int largestRectangleArea(int[] height) { int area = 0; Stack<Integer> st = new Stack<Integer>(); for(int i=0; i<height.length; i++){ if(st.empty() || height[i]>height[st.peek()]) st.push(i); else{ int end = st.pop(); int width = st.empty() ? i : i-st.peek()-1; area = Math.max(area, height[end]*width); i--; } } //处理最后 while(!st.empty()){ int end = st.pop(); int width = st.empty() ? height.length : height.length-st.peek()-1; area = Math.max(area, height[end]*width); } return area; } }