双指针

难度困难

题目描述

image.png

解题思路

缓存两端最大值,从最大值较小的一边进行储水结算、移动,并更新最大值。

Code

  1. public int trap(int[] height) {
  2. //长度为1或者2时,蓄水量一定为0
  3. if (height.length < 3) {
  4. return 0;
  5. }
  6. //长度大于2的情况
  7. int left = 0;//左指针
  8. int right = height.length - 1;//右指针
  9. int leftmax = height[left];//左边最大值
  10. int rightmax = height[right];//右边最大值
  11. int res = 0;//记录蓄水量
  12. while (left < right) {
  13. if (leftmax < rightmax) {
  14. //左侧最高值减去当前位置值就是该位置的蓄水量
  15. res += leftmax - height[left++];
  16. //更新左侧最大值
  17. leftmax = Math.max(leftmax, height[left]);
  18. } else {
  19. //右侧最高值减去当前位置值就是该位置的蓄水量
  20. res += rightmax - height[right--];
  21. //更新右侧最大值
  22. rightmax = Math.max(rightmax, height[right]);
  23. }
  24. }
  25. //注:某位置的蓄水量等于当前最高值减去该位置的值
  26. return res;
  27. }