核心思想:双指针
class Solution {
public int trap(int[] height) {
int left = 0;
int right = height.length - 1;
int l_max = 0;
int r_max = 0;
int sum = 0;
if(right <= 1){
return 0;
}
while(left < right){
// 如果height[left]<height[right],那么起码说明left可能有积水
//想想极限情况[7,0,0,0,0,0,1],这个判断就显得很有用
if(height[left] < height[right]){
//现在就看左边是否有比l_max高的列
if(height[left] > l_max){
l_max = height[left];
}else{
//如果出现比l_max低的列,则一定可以积水
sum += (l_max - height[left]);
}
left++;
}else{
//同上
if(height[right] > r_max){
r_max = height[right];
}else{
sum += (r_max - height[right]);
}
right--;
}
}
return sum;
}
}