Skip to content

Commit 0a65599

Browse files
committed
add leetcode: 84
1 parent 3fbfdd5 commit 0a65599

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package leetCode.subject.number51_100;
2+
3+
/**
4+
* @author : CodeWater
5+
* @create :2022-08-12-23:10
6+
* @Function Description :84. 柱状图中最大的矩形
7+
*/
8+
public class _84TheLargestRectangleInTheColumnDiagram {
9+
class Solution {
10+
/**单调栈,解决的问题:找到每一个数左边离他最近的数(的下标,比他小)
11+
枚举上边界(每个数组元素)时:要看左右边界比当前自己高度小的位置
12+
*/
13+
public int largestRectangleArea(int[] heights) {
14+
int n = heights.length;
15+
// left和right数组分别记录每个元素小于该下标元素的左右边界
16+
int[] left = new int[n] , right = new int[n];
17+
// 单调栈,求元素的左右边界
18+
Stack<Integer> stk = new Stack<>();
19+
20+
// 左边界
21+
for( int i = 0 ; i < n ; i++ ){
22+
// 栈中大于等于当前元素的都出栈,直到出现小于的或者栈空
23+
while( stk.size() > 0 && heights[stk.peek()] >= heights[i] ) stk.pop();
24+
if( stk.empty() ) left[i] = -1;
25+
else left[i] = stk.peek();
26+
stk.push(i);
27+
}
28+
29+
stk.clear();
30+
// 右边界
31+
for( int i = n - 1 ; i >= 0 ; i-- ){
32+
while( stk.size() > 0 && heights[stk.peek()] >= heights[i] ) stk.pop();
33+
if( stk.empty() ) right[i] = n;
34+
else right[i] = stk.peek();
35+
stk.push(i);
36+
}
37+
38+
// 遍历每个元素,求解
39+
int res = 0;
40+
for( int i = 0 ; i < n ; i++ ){
41+
res = Math.max( res , heights[i] * (right[i] - left[i] - 1 ) );
42+
}
43+
44+
return res;
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)