Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8d1c4d6

Browse files
Update 0084.柱状图中最大的矩形.md
增加java 单调栈实现
1 parent ac71ac4 commit 8d1c4d6

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎problems/0084.柱状图中最大的矩形.md‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,50 @@ class Solution {
228228
}
229229
```
230230

231+
单调栈
232+
```java
233+
class Solution {
234+
int largestRectangleArea(int[] heights) {
235+
Stack<Integer> st = new Stack<Integer>();
236+
237+
// 数组扩容,在头和尾各加入一个元素
238+
int [] newHeights = new int[heights.length + 2];
239+
newHeights[0] = 0;
240+
newHeights[newHeights.length - 1] = 0;
241+
for (int index = 0; index < heights.length; index++){
242+
newHeights[index + 1] = heights[index];
243+
}
244+
245+
heights = newHeights;
246+
247+
st.push(0);
248+
int result = 0;
249+
// 第一个元素已经入栈,从下表1开始
250+
for (int i = 1; i < heights.length; i++) {
251+
// 注意heights[i] 是和heights[st.top()] 比较 ,st.top()是下表
252+
if (heights[i] > heights[st.peek()]) {
253+
st.push(i);
254+
} else if (heights[i] == heights[st.peek()]) {
255+
st.pop(); // 这个可以加,可以不加,效果一样,思路不同
256+
st.push(i);
257+
} else {
258+
while (heights[i] < heights[st.peek()]) { // 注意是while
259+
int mid = st.peek();
260+
st.pop();
261+
int left = st.peek();
262+
int right = i;
263+
int w = right - left - 1;
264+
int h = heights[mid];
265+
result = Math.max(result, w * h);
266+
}
267+
st.push(i);
268+
}
269+
}
270+
return result;
271+
}
272+
}
273+
```
274+
231275
Python:
232276

233277
动态规划

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /