leetcode题集——trapping-rain-water

来源:互联网 发布:java小软件源代码 编辑:程序博客网 时间:2024/06/13 14:48

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], return6.

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!

解析:使用双指针法。分别从数组两边开始遍历,当leftmax>rightmax时,可以求出right=n-2位置的水量;反之,当leftmax<rightmax时,可以求出left=1位置的水量。

循环条件为left<=right。

class Solution {public:    int max(int a,int b)    {       return a>b?a:b;    }    int trap(int A[], int n)     {       if(A==NULL||n<3)           return 0;       int sum;       int leftmax=A[0];       int rightmax=A[n-1];       int l=1;       int r=n-2;              while(l<=r)      {        if(leftmax<rightmax)        {//左侧最小值比右侧值小           sum+=max(0,leftmax-A[l]);            leftmax=max(leftmax,A[l++]);        }        else        {           sum+=max(0,rightmax-A[r]);           rightmax=max(rightmax,A[r--]);        }                    }        return sum;    }};


0 0
原创粉丝点击