题目:求一个数组序列所能容纳的水的体积
思路:从两端向中间逼近
class Solution {
public:
int trap(int A[], int n) {
if(n==0)return 0;
int result=0;
int i,j;
int head=0;
int tail=n-1;
while(head<tail){
while(A[head]<=A[head+1]&&head<tail)head++;
while(A[tail]<=A[tail-1]&&tail>head)tail--;
int temp;
if(head<tail){
if(A[head]<=A[tail]){
temp=A[head];
head++;
while(A[head]<temp&&head<tail){
result+=temp-A[head];
head++;
}
}
else{
temp=A[tail];
tail--;
while(A[tail]<temp&&tail>head){
result+=temp-A[tail];
tail--;
}
}
}
}
return result;
}
};