Trapping Rain Water

来源:互联网 发布:java字符串里的大括号 编辑:程序博客网 时间:2024/06/05 19:41

Q:

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.


The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!


Solution:

public class Solution {    public int trap(int[] A) {        if (A == null || A.length == 0)            return 0;        Stack<Integer> stack = new Stack<Integer>();        Stack<Integer> width = new Stack<Integer>();        int start = 0;        while (start < A.length && A[start] == 0) start++;        if (start < A.length) {            stack.push(A[start]);            width.push(1);        }        int trap = 0;        for (int i = start+1; i < A.length; i++) {            if (A[i] <= stack.peek()) {                stack.push(A[i]);                width.push(1);            }            else {                int w = 0;                while (!stack.isEmpty() && stack.peek() <= A[i]) {                    int height = stack.pop();                    w += width.pop();                    if (!stack.isEmpty())                        trap += (Math.min(stack.peek(), A[i]) - height) * w;                                        }                stack.push(A[i]);                width.push(w+1);            }        }        return trap;    }}


0 0
原创粉丝点击