双指针
难度困难
题目描述
解题思路
缓存两端最大值,从最大值较小的一边进行储水结算、移动,并更新最大值。
Code
public int trap(int[] height) {//长度为1或者2时,蓄水量一定为0if (height.length < 3) {return 0;}//长度大于2的情况int left = 0;//左指针int right = height.length - 1;//右指针int leftmax = height[left];//左边最大值int rightmax = height[right];//右边最大值int res = 0;//记录蓄水量while (left < right) {if (leftmax < rightmax) {//左侧最高值减去当前位置值就是该位置的蓄水量res += leftmax - height[left++];//更新左侧最大值leftmax = Math.max(leftmax, height[left]);} else {//右侧最高值减去当前位置值就是该位置的蓄水量res += rightmax - height[right--];//更新右侧最大值rightmax = Math.max(rightmax, height[right]);}}//注:某位置的蓄水量等于当前最高值减去该位置的值return res;}
