LeetCode#42接雨水

2019-08-29  本文已影响0人  Android_ZzT

题目:
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

思路:

代码:

class Solution {
    public int trap(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int leftMax = 0, rightMax = 0;
        int result = 0;
        while (left < right) { //左右在中间相碰时,退出循环
            if (height[left] < height[right]) { //从左向右接雨水
                if (height[left] > leftMax) {//值大更新
                    leftMax = height[left];
                } else { //值小累加雨水的值
                    result += leftMax - height[left];
                }
                left++; //向右移动
            } else {
                if (height[right] > rightMax) { //从右向左同理
                    rightMax = height[right];
                } else {
                    result += rightMax - height[right];
                }
                right--; //向左移动
            }
        }
        return result;
    }
}

上一篇 下一篇

猜你喜欢

热点阅读