84. Largest Rectangle in Histogram
2017-06-23 13:19
357 查看
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 =
The largest rectangle is shown in the shaded area, which has area =
For example,
Given heights =
return
这道题考查单调栈的用法。这里的单调栈是单调递增栈,遇到比peek小的数,就开始弹栈,直到栈为空或者遇到比自己小的peek,并随时更新max。代码如下:
public class Solution {
public int largestRectangleArea(int[] heights) {
if (heights == null || heights.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
int max = 0;
for (int i = 0; i <= heights.length; i ++) {
int cur = i == heights.length? -1: heights[i];
while (!stack.isEmpty() && cur <= heights[stack.peek()]) {
int h = heights[stack.pop()];
int w = stack.isEmpty()? i: i - stack.peek() - 1;
max = Math.max(max, h * w);
}
stack.push(i);
}
return max;
}
}
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 =
10unit.
For example,
Given heights =
[2,1,5,6,2,3],
return
10.
这道题考查单调栈的用法。这里的单调栈是单调递增栈,遇到比peek小的数,就开始弹栈,直到栈为空或者遇到比自己小的peek,并随时更新max。代码如下:
public class Solution {
public int largestRectangleArea(int[] heights) {
if (heights == null || heights.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
int max = 0;
for (int i = 0; i <= heights.length; i ++) {
int cur = i == heights.length? -1: heights[i];
while (!stack.isEmpty() && cur <= heights[stack.peek()]) {
int h = heights[stack.pop()];
int w = stack.isEmpty()? i: i - stack.peek() - 1;
max = Math.max(max, h * w);
}
stack.push(i);
}
return max;
}
}
相关文章推荐
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- Leetcode 84 Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- [Letecode 84] Largest Rectangle in Histogram
- LeetCode84 Largest Rectangle in Histogram 解题报告
- 【leetcode】Array——Largest Rectangle in Histogram(84)
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- leetcode 84 :Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- LeetCode 84 Largest Rectangle in Histogram
- leetcode[84]Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- leetcode || 84、Largest Rectangle in Histogram
- LeetCode 84 (Largest Rectangle in Histogram)java
- 84:Largest Rectangle in Histogram【数组】【栈】