马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
题目
解答
- 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() {
- }
- @Test
- public 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);
- }
- }
复制代码 本题目初看之下照旧有点唬人的,一下子想不到解答的方法。
把题目分解为两个题目:
- 指定坐标的位置,能不能盛水。
- 假如上个命题建立,那么能装多少水。
第一个题目从知识出发,很好解答,即凹进去的位置,才华装水;比周边高的位置,肯定不能装水。
第二个题目,对于能装水的点,装多少水,取决于周边的最小高度,然后减去自身的高度,便是当前坐标点可以盛的水。
|