Java
class Solution {
public int trap(int[] height) {
if( height.length < 3 ) return 0 ;
int ans = 0 ;
int l = 0 , r = height.length - 1 ;
// 找寻真正左边 右边
while ( l < r && height[l] <= height[++l] );
while ( l < r && height[r] <= height[--r] );
while ( l < r ) {
int left = height[l] ;
int right = height[r] ;
if(left <= right) {
while ( l < r && left >= height[++l] ) {
ans += left - height[l];
}
} else {
while ( l < r && right >= height[--r] ) {
ans += right - height[--r];
}
}
}
return ans;
}
}
Go
func trap(height []int) int {
if len(height) < 3 { return 0 }
// 初始变量
ans,l,r := 0 , 0 , len(height) - 1
// 寻找边界
for l < r && height[l] <= height[l + 1] { l ++ }
for l < r && height[r] <= height[r - 1] { r -- }
left , right := 0,0
for l < r {
left = height[l]
right = height[r]
if left <= right {
l = l + 1
for l < r && left >= height[l] {
ans = ans + (left - height[l])
l = l + 1
}
} else {
r = r - 1
for l < r && right >= height[r] {
ans = ans + (right - height[r])
r = r - 1
}
}
}
return ans
}