File tree Expand file tree Collapse file tree 2 files changed +24
-9
lines changed Expand file tree Collapse file tree 2 files changed +24
-9
lines changed Original file line number Diff line number Diff line change @@ -23,7 +23,12 @@ public int largestRectangleArea(int[] heights) {
23
23
return max ;
24
24
}
25
25
26
- /** 注意栈中的是index,不是高度
26
+ /**
27
+ * 核心思路是用栈保存一个高度递增的index,当出现一个局部最高点时,计算以该最高点为高度的最大面积
28
+ * 该局部最高点的形成可能是新加的柱子较矮,也可能是随着旧的高点不断出栈导致的
29
+ * 该局部高点的特点是"相邻的柱子都比他高",这里相邻的意思是左边延伸到下一个出栈的index,右边延伸到新加的柱子
30
+ *
31
+ * 注意栈中的是index,不是高度
27
32
* 栈保持递增,当出现小于栈顶的元素时,意味着可以计算栈顶可以延伸的矩形面积了
28
33
* 其左边界是次栈顶,右边界是当前元素
29
34
*/
Original file line number Diff line number Diff line change @@ -4,18 +4,28 @@ public class Main {
4
4
5
5
public static class Solution {
6
6
7
- public int leastInterval (char [] tasks , int n ) {
8
- int [] count = new int [26 ];
9
- for (char c : tasks ) {
10
- count [c - 'A' ]++;
7
+ public int largestRectangleArea (int [] heights ) {
8
+ int [] indexes = new int [heights .length + 1 ];
9
+ int top = -1 , max = 0 ;
10
+
11
+ for (int i = 0 ; i <= heights .length ; ) {
12
+ int height = i == heights .length ? 0 : heights [i ];
13
+ if (top < 0 || height > heights [indexes [top ]]) {
14
+ indexes [++top ] = i ++;
15
+ } else {
16
+ int k = heights [indexes [top --]];
17
+ int left = top < 0 ? 0 : (indexes [top ] + 1 );
18
+ max = Math .max (max , (i - 1 - left + 1 ) * k );
19
+ }
11
20
}
12
- Arrays .sort (count );
13
- int i = 25 ;
14
- for ( ; i >= 0 && count [i ] == count [25 ]; i --);
15
- return Math .max (tasks .length , (count [25 ] - 1 ) * (n + 1 ) + 25 - i );
21
+
22
+ return max ;
16
23
}
24
+
17
25
}
18
26
27
+
28
+
19
29
public static void main (String [] args ) {
20
30
Solution solution = new Solution ();
21
31
}
You can’t perform that action at this time.
0 commit comments