Trapping Rain Water

来源:互联网 发布:易达工程造价软件 编辑:程序博客网 时间:2024/06/05 21:27
题目如下:

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.


解析思路:先找到最高峰,然后从两边向中间计算,因为两边向中间是递增的趋势

参考代码如下:

    int trap(int A[], int n) {        if(n <= 2) return 0;        int max = -1, maxInd = 0;        int i = 0;        for(; i < n; ++i){//先找出最高峰            if(A[i] > max){                max = A[i];                maxInd = i;            }        }        int area = 0, root = A[0];        for(i = 0; i < maxInd; ++i){//从左侧到最高峰的计算            if(root < A[i]) root = A[i];            else area += (root - A[i]);        }        for(i = n-1, root = A[n-1]; i > maxInd; --i){//从右侧到最高峰的计算            if(root < A[i]) root = A[i];            else area += (root - A[i]);        }        return area;    }


原创粉丝点击