[LeetCode]Trapping Rain Water,解题报告

2014-11-24 07:33:49 · 作者: · 浏览: 0

前言

在LeetCode上又碰到了一道笔试原题,充分说明提前的准备对应届生找工作有多大的作用,年终总结我会具体写一下自己找工作的准备历程,耗时将近半年时间

题目

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.

\


解题思路

首先,碰到这样的题目不要慌张,挨个分析每个A[i]能trapped water的容量,然后将所有的A[i]的trapped water容量相加即可
其次,对于每个A[i]能trapped water的容量,取决于A[i]左右两边的高度(可延展)较小值与A[i]的差值,即volume[i] = [min(left[i], right[i]) - A[i]] * 1,这里的1是宽度,如果the width of each bar is 2,那就要乘以2了

AC代码

public class Solution {
    public int trap(int[] A) {
        // special case
        if (A == null || A.length == 0) {
            return 0;
        }
        
        int i, max, volume, left[] = new int[A.length], right[] = new int[A.length];

        // from left to right
        for (left[0] = A[0], i = 1, max = A[0]; i < A.length; i++) {
            if (A[i] < max) {
                left[i] = max;
            } else {
                left[i] = A[i];
                max = A[i];
            }
        }

        // from right to right
        for (right[A.length - 1] = A[A.length - 1], i = A.length - 2, max = A[A.length - 1]; i >= 0; i--) {
            if (A[i] < max) {
                right[i] = max;
            } else {
                right[i] = A[i];
                max = A[i];
            }
        }

        // trapped water
        for (volume = 0, i = 1; i <= A.length - 2; i++) {
            int tmp = Math.min(left[i], right[i]) - A[i];
            if (tmp > 0) {
                volume += tmp;
            }
        }

        return volume;
    }
}