LeetCode面试题 17.21 直方图的水量
题目
解答
package leetcode.editor.cn;//leetcode submit region begin(Prohibit modification and deletion)
class Solution {public int trap(int[] height) {int length = height.length;if (length == 0) {return 0;}int[] leftMax = new int[length];leftMax[0] = 0;for (int i = 1, end = length - 1; i < end; ++i) {leftMax[i] = Math.max(leftMax[i - 1], height[i - 1]);}int[] rightMax = new int[length];rightMax[length - 1] = 0;for (int i = length - 2; i >= 0; --i) {rightMax[i] = Math.max(rightMax[i + 1], height[i + 1]);}int result = 0;for (int i = 1, end = length - 1; i < end; ++i) {if (leftMax[i] > height[i] && rightMax[i] > height[i]) {result += Math.min(leftMax[i], rightMax[i]) - height[i];}}return result;}
}
//leetcode submit region end(Prohibit modification and deletion)
测试用例
package leetcode.editor.cn;import org.junit.Assert;
import org.junit.Test;public class SolutionTest {public SolutionTest() {}@Testpublic void test() {Solution s = new Solution();int result = s.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1});Assert.assertTrue(String.valueOf(result), result == 6);}
}
本题目初看之下还是有点唬人的,一下子想不到解答的方法。
把题目分解为两个问题:
- 指定坐标的位置,能不能盛水。
- 假如上个命题成立,那么能装多少水。
第一个问题从常识出发,很好解答,即凹进去的位置,才能装水;比周边高的位置,肯定不能装水。
第二个问题,对于能装水的点,装多少水,取决于周边的最小高度,然后减去自身的高度,即是当前坐标点可以盛的水。