LeetCode42. 接雨水

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

这里写图片描述

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。

示例:

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

先遍历一遍数组,引入数组leftMax,rightMax求出当前元素向左看的最大值,向右看的最大值。如果自身是最大值,置为0。
第二次遍历数组,求出该位置的蓄水情况,累加。

package 牛客刷题.LeetCode.栈.trapping_rain_water;

/**
 * Created by Administrator on 2018/5/26 0026.
 */
public class Solution {
    public static void main(String[] args) {
        //int[] A = {0,1,0,2,1,0,1,3,2,1,2,1};
        int[] A = {0};
        System.out.println(trap(A));
    }

    public static int trap(int[] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        int[] leftMax = new int[A.length];
        int[] rightMax = new int[A.length];
        int max = A[0];
        for (int i = 1; i < A.length; i++) {
            if (A[i] < max) {
                leftMax[i] = max;
            } else {
                max = A[i];
            }
        }
        max = A[A.length -1];
        for (int i = A.length -2; i >= 0 ; i--) {
            if (A[i] < max) {
                rightMax[i] = max;
            } else {
                max = A[i];
            }
        }
        int res = 0;
        for (int i = 1; i < A.length -1; i++) {
            if (leftMax[i] != 0 && rightMax[i] != 0) {
                res += Math.min(leftMax[i], rightMax[i]) - A[i];
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31617121/article/details/80461785
今日推荐