leetcode hot100 42.接雨水

71 阅读1分钟

image.png

解题思路

1.定义双指针,分别指向头和末尾
2.判断左右指针谁指向的墙高,在矮一边找出较高的墙(不比另一个指针指向的墙高),当出现比 当前记录较大值 小的墙,说明处于低洼处,将低洼处与双指针指向的较矮的墙相减,即为当前墙上的储水量,累加到结果当中。
3.然后指针继续走,重复当前操作。

/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function (height) {
  let len = height.length;
  if (len < 3) return 0;
  let left = 0, right = len - 1;
  let result = 0;
  let left_max = 0, right_max = 0;

  while (left < right) {
    if (height[left] < height[right]) {
      if (height[left] > left_max) left_max = height[left];
      else result += left_max - height[left];
      left++;
    }
    else {
      if (height[right] > right_max) right_max = height[right];
      else {
        result += right_max - height[right];
      }

      right--;
    }
  }
  return result;
};

还是自己太菜了,虽然想到用双指针做,但是最终还是没写出来,还得看题解学习解题思路;希望坚持下去能有所收获吧。