一道hard的题,这道题确实有些难度,参考了评论区的解法链接
思路是建立左右两个指针,和两个遍历leftmax rightmax记录一侧的墙的高度,然后左右指针同时往中间走,具体走哪边取决于边的高度,每次走高度低的那一边,直到左右指针相遇。
class Solution {
public int trap(int[] height) {
int left = 0;
int right = height.length -1;
int water = 0;
int leftmax = 0, rightmax = 0;
while(left <= right) {
if(height[left] <= height[right]) {
if(height[left] > leftmax)
leftmax = height[left];
else
water += leftmax - height[left];
left++;
} else {
if(height[right] > rightmax)
rightmax = height[right];
else
water += rightmax - height[right];
right--;
}
}
return water;
}
}