Trapping Rain Water解题报告

作者: Jiafu | 来源:发表于2017-09-30 08:58 被阅读13次

    题目: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

    image.png

    解题思路:从头到尾扫描数组,找到两个数,使得这两个数中间的所有数都小于等于这两个数,相当于是找到两个最高的矩形,然后计算这两个矩形中间的水的面积,然后叠加起来。Java代码:

    public class Solution {
        public int trap(int[] height) {
            int sum = 0;
            int startPosition = 0;
            int index = 0;
            int endHeight = 0;
            int endPosition = 0;
            // 定位到第一个非0的位置
            while (startPosition < height.length && height[startPosition] == 0) {
                ++startPosition;
            }
    
            while (startPosition < height.length - 1) {
                index = startPosition + 1;
                endPosition = index;
                endHeight = height[endPosition];
                while (index < height.length) {
                    if (height[startPosition] > height[index]) {
                        if (height[index] >= endHeight) {
                            endPosition = index;
                            endHeight = height[endPosition];
                        }
                        ++index;
                    } else {
                        endPosition = index;
                        endHeight = height[endPosition];
                        break;
                    }
                }
                sum += calculateTrapRain(height, startPosition, endPosition);
                startPosition = endPosition;
            }
    
            return sum;
        }
    
        private int calculateTrapRain(int[] height, int start, int end) {
            int lowerHeight = Math.min(height[start], height[end]);
            int sum = 0;
            for (int i = start + 1; i < end; ++i) {
                sum += (lowerHeight - height[i]);
            }
            return sum;
        }
       
        public static void main(String[] args) {
            Solution solution = new Solution();
            int[] height = new int[] {0,1,0,2,1,0,1,3,2,1,2,1};
            System.out.println(solution.trap(height));
        }
    }
    
    

    相关文章

      网友评论

        本文标题:Trapping Rain Water解题报告

        本文链接:https://www.haomeiwen.com/subject/abiiextx.html