Mono Stack
Copy ```java
class Solution {
public int trap ( int [] height) {
int n = height . length ;
Stack < Integer > stack = new Stack <>(); // index
int result = 0 ;
for ( int i = 0 ; i < n; i ++ ) {
while ( ! stack . isEmpty () && height[ stack . peek ()] < height[i]) {
int base = height[ stack . pop ()];
if ( ! stack . isEmpty ()) {
int leftBoundIndex = stack . peek ();
int leftHeight = height[leftBoundIndex];
result += ( Math . min (height[i] , leftHeight) - base) * (i - leftBoundIndex - 1 );
}
}
stack . push (i);
}
return result;
}
}
/***
min(hi, left side) - base idea
2,1,0,1,3
x x x
3
2.x x x 3
2 1 x 1 3
2 1 0.1 3
curH
base = pop
left = peek
(min(leftH, curH) - base)* (index diff)
3
2.x x x 3
2 1 x 1 3
3. cur H
1 -> base
1. -> peek
2 -> peek
min(3, 1) - base (1) = 0
min(3, 2) - base (1) = 1
*/
```
Two pointers
-----
if (h[left] < h[right] )
ๆๅทฆ้ๅงๆพๆๅคง็ left, left++
else
ๆๅณ้ไฝฟๆพๆๅคง็ right, right--
็ฎ็ๆฏ็บไบๆพๅฐ descending ็ๆๅ, ไนๅฐฑๆฏๆ็ฉๆฐด, ๆ นๆฌไธ็จ็ฎกไธญ้็ๅผ
็ๆๅทฆ ๆๅณๅฐฑๅพๅพ็ฅ
descending!
ๅ
ถๅฏฆๅทฆ ่ท ๅณๅ็ไบ้ทๅ, ๆไปฅๅชๆฏ่ฎๆธๆนๆ right, right--
Copy if (height[left] < height[right]) { // ๅ ็บๅทฆ้ๆฏ่ผๅฐ, ๅ
ๅ left
....
left ++ ;
Copy class Solution {
public int trap ( int [] height) {
// two pointers
// h[left] > h[right]
// leftmax > h[left] => res += leftmax - res
int left = 0 ;
int right = height . length - 1 ;
int leftMax = 0 ;
int rightMax = 0 ;
int res = 0 ;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math . max (leftMax , height[left]);
res += leftMax - height[left];
left ++ ;
} else {
rightMax = Math . max (rightMax , height[right]);
res += rightMax - height[right];
right -- ;
}
}
return res;
}
}
ๅฆๆๆฏ็จ left right ๆ้
่ฆ็ฎ้จๆฐด้ข็ฉ, ๅฐ left ็ๅทฆ้, ๆๅๅช้ๅฟๆๅคง็ maxleft ๆฏๅคๅฐ ๏ผๅฆๆๆๅ้ฝๆฑบๅฎๆฏ่ตฐๅทฆ้็่ฉฑ, ๅ ็บๆๅ้ฝๆณ่ฆๅๆฏ่ผไฝ็้ฃไธ้, ๆไปฅๅฆๆ max_ left ๆฏ่ผๅฐ, ้ฃ่ตฐๅทฆ้็ๆฏ่ผๅ่จ็ฎ
ๅไน่ตฐๅณ้
Copy class Solution {
public int trap ( int [] height) {
int n = height . length ;
int left = 0 ;
int right = n - 1 ;
int maxLeft = 0 ;
int maxRight = 0 ;
int result = 0 ;
while (left < right) {
maxLeft = Math . max (maxLeft , height[left]);
maxRight = Math . max (maxRight , height[right]);
if (maxLeft < maxRight) {
result += maxLeft - height[left];
left ++ ;
} else {
result += maxRight - height[right];
right -- ;
}
}
return result;
}
}
use this
ไธ้ๆ่ช็บ้ๅ่งฃๆณๆฏ่ผๅฅฝๆ
ๅฆไฝ่ฝๆงๆๆ้จๆฐดๅข๏ผ ๆพๅทฆ้ๆ้ซ็ ๅๅณ้ๆ้ซ็, ๆฏ่ผไฝ็ ๅฏไปฅๆ้จๆฐด๏ผ่ฆๆฃๆ่ชๅทฑๆฌ่บซ็้ซๅบฆ
T: O(n)
S: O(n)
Copy class Solution {
public int trap ( int [] height) {
int n = height . length ;
int [] maxLeft = new int [n];
int [] maxRight = new int [n];
maxLeft[ 0 ] = height[ 0 ];
for ( int i = 1 ; i < n; i ++ ) {
maxLeft[i] = Math . max (height[i] , maxLeft[i - 1 ]);
}
maxRight[n - 1 ] = height[n - 1 ];
for ( int i = n - 2 ; i >= 0 ; i -- ) {
maxRight[i] = Math . max (height[i] , maxRight[i + 1 ]);
}
int result = 0 ;
for ( int i = 0 ; i < n; i ++ ) {
result += Math . min (maxLeft[i] , maxRight[i]) - height[i];
}
return result;
}
}
Last updated 9 months ago