Leetcode: Trapping Rain Water

来源:互联网 发布:对外经济贸易大学知乎 编辑:程序博客网 时间:2024/06/06 05:34

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.

Scan the integers from left to right and store the maximum trapped water from left to that bar in an array. Then scan from right to left and again store the maximum trapped water from right to that bar. For each bar, the maximum trapped water from both side is the minimum value from left and right side. Add the maximum values of each bar and get the result. O(n) time and O(n) space.

public class Solution {    public int trap(int[] A) {        if (A == null || A.length == 0) {            return 0;        }                int[] max = new int[A.length];        max[0] = 0;        int left = A[0];        for (int i = 1; i < A.length; i++) {        max[i] = left > A[i] ? (left - A[i]) : 0;        left = Math.max(left, A[i]);        }                int res = 0;        int right = A[A.length - 1];        for (int i = A.length - 2; i >= 0; i--) {        int cur = right > A[i] ? (right - A[i]) : 0;        right = Math.max(right, A[i]);        res += Math.min(cur, max[i]);        }                return res;    }}


0 0
原创粉丝点击