题目

https://leetcode-cn.com/problems/trapping-rain-water/

思路-双指针

双指针往中间走,并分别维持左右走过的最大值,遇到较小值说明踩到了水。

  1. class Solution {
  2. public int trap(int[] height) {
  3. int res = 0;
  4. int l = 0;
  5. int r = height.length - 1;
  6. int maxL = 0; // [0..l]之间遇到的最高的柱子
  7. int maxR = 0; // [n-1..r]之间遇到的最高的柱子
  8. while (l < r) {
  9. if (height[l] < height[r]) {
  10. if (height[l] < maxL) { // 踩水坑里了,计算水坑面积
  11. res += maxL - height[l];
  12. } else { // 遇到更高的柱子,更新maxL
  13. maxL = height[l];
  14. }
  15. l++;
  16. } else {
  17. if (height[r] < maxR) { // 踩水坑里了,计算水坑面积
  18. res += maxR - height[r];
  19. } else {
  20. maxR = height[r];
  21. }
  22. r--;
  23. }
  24. }
  25. return res;
  26. }
  27. }