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!
1、双指针,一次遍历
int trap(int A[], int n) {
if(n<=2) return 0;
int low=0;
int high=n-1;
int waterSum=0;
int indexMin=0;
while(low<high)
{
while(A[low]<=indexMin&&low<high)
{
waterSum+=(indexMin-A[low]);
low++;
}
while(A[high]<=indexMin&&low<high)
{
waterSum+=(indexMin-A[high]);
high--;
}
indexMin=A[low]>=A[high]?A[high]:A[low];
}
return waterSum;
}
2、可以先找到序列中的最大值,再从两端向中间遍历,此时时间复杂度为O(2n);