File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -391,6 +391,7 @@ class Solution {
391
391
}
392
392
}
393
393
```
394
+
394
395
动态规划法
395
396
``` java
396
397
class Solution {
@@ -418,6 +419,52 @@ class Solution {
418
419
}
419
420
}
420
421
```
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
+
421
468
Python:
422
469
423
470
双指针法
You can’t perform that action at this time.
0 commit comments