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 ac71ac4

Browse files
Update 0042.接雨水.md
增加Java 单调栈实现
1 parent 2c27288 commit ac71ac4

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎problems/0042.接雨水.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,7 @@ class Solution {
391391
}
392392
}
393393
```
394+
394395
动态规划法
395396
```java
396397
class Solution {
@@ -418,6 +419,52 @@ class Solution {
418419
}
419420
}
420421
```
422+
423+
单调栈法
424+
```java
425+
public int trapMonoStack(int[] height){
426+
int size = height.length;
427+
428+
if (size <= 2) return 0;
429+
430+
// in the stack, we push the index of array
431+
// using height[] to access the real height
432+
Stack<Integer> stack = new Stack<Integer>();
433+
stack.push(0);
434+
435+
int sum = 0;
436+
for (int index = 1; index < size; index++){
437+
int stackTop = stack.peek();
438+
if (height[index] < height[stackTop]){
439+
stack.push(index);
440+
}else if (height[index] == height[stackTop]){
441+
// 因为相等的相邻墙,左边一个是不可能存放雨水的,所以pop左边的index, push当前的index
442+
stack.pop();
443+
stack.push(index);
444+
}else{
445+
//pop up all lower value
446+
int heightAtIdx = height[index];
447+
while (!stack.isEmpty() && (heightAtIdx > height[stackTop])){
448+
int mid = stack.pop();
449+
450+
if (!stack.isEmpty()){
451+
int left = stack.peek();
452+
453+
int h = Math.min(height[left], height[index]) - height[mid];
454+
int w = index - left - 1;
455+
int hold = h * w;
456+
if (hold > 0) sum += hold;
457+
stackTop = stack.peek();
458+
}
459+
}
460+
stack.push(index);
461+
}
462+
}
463+
464+
return sum;
465+
}
466+
```
467+
421468
Python:
422469

423470
双指针法

0 commit comments

Comments
(0)

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