Skip to content

Commit 589b5bc

Browse files
committed
fd
1 parent 1cb6732 commit 589b5bc

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

leetcode/solution/src/LargestRectangleInHistogram.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,12 @@ public int largestRectangleArea(int[] heights) {
2323
return max;
2424
}
2525

26-
/** 注意栈中的是index,不是高度
26+
/**
27+
* 核心思路是用栈保存一个高度递增的index,当出现一个局部最高点时,计算以该最高点为高度的最大面积
28+
* 该局部最高点的形成可能是新加的柱子较矮,也可能是随着旧的高点不断出栈导致的
29+
* 该局部高点的特点是"相邻的柱子都比他高",这里相邻的意思是左边延伸到下一个出栈的index,右边延伸到新加的柱子
30+
*
31+
* 注意栈中的是index,不是高度
2732
* 栈保持递增,当出现小于栈顶的元素时,意味着可以计算栈顶可以延伸的矩形面积了
2833
* 其左边界是次栈顶,右边界是当前元素
2934
*/

leetcode/src/Main.java

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,28 @@ public class Main {
44

55
public static class Solution {
66

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+
}
1120
}
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;
1623
}
24+
1725
}
1826

27+
28+
1929
public static void main(String[] args) {
2030
Solution solution = new Solution();
2131
}

0 commit comments

Comments
 (0)