Trapping Rain Water Leetcode
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
这道题可能是第一道hard题目,一开始逻辑理了半天十分挫败,但是代码写出来,自己run了一次发现少了个等号,加了等号之后一遍submit就accepted了,好开心哈哈哈~也许是leetcode评难度偏低,感觉是medium的难度到不了hard。。。
这个题采用two pointers的方法,从左右到中间。主要的难点是判断什么时候left++什么时候right--,什么时候更新短板。
题中例子为例,当左边的木板不高于右边的木板的时候,就总是按照左边的高木板开始,往低于高木板的地方充水。如果遇到比这个高木板高的木板,但是低于右边的barrier,更新高木板,继续充水。
public class Solution { public int trap(int[] height) { if (height == null || height.length == 0) { return 0; } int left = 0; int right = height.length - 1; int count = 0; while (left < right) { int leftBarrier = height[left]; while (left < right && height[left] <= height[right]) { if (height[left] < leftBarrier) { count += leftBarrier - height[left]; } else { leftBarrier = height[left]; } left++; } int rightBarrier = height[right]; while (left < right && height[right] < height[left]) { if (height[right] < rightBarrier) { count += rightBarrier - height[right]; } else { rightBarrier = height[right]; } right--; } } return count; } }
看了下top solution,思路是一样的,不过代码更简洁一些。
public class Solution { public int trap(int[] height) { if (height == null || height.length == 0) { return 0; } int left = 0; int right = height.length - 1; int count = 0; int leftBarrier = 0; int rightBarrier = 0; while (left < right) { leftBarrier = Math.max(leftBarrier, height[left]); rightBarrier = Math.max(rightBarrier, height[right]); if (leftBarrier < rightBarrier) { count += leftBarrier - height[left]; left++; } else { count += rightBarrier - height[right]; right--; } } return count; } }