//fun...
class Solution {
public:
int trap(int A[], int n) {
if(n<3) return 0;
vector<int> left_max(n,0),right_max(n,0);
//left_max[i]: 从左到i,最大值的index
//right_max[i]: 从右到i,最大值的index
//from left to right
int max_index=0;
for(int i=0;i<n;i++){
if(A[i]>A[max_index]){
left_max[i]=i;
max_index=i;
}else{
left_max[i]=max_index;
}
}
//from right to left
max_index=n-1;
for(int i=n-1;i>=0;i--){
if(A[i]>A[max_index]){
right_max[i]=i;
max_index=i;
}else{
right_max[i]=max_index;
}
}
//get result
int sum=0;
for(int i=0;i<n;i++){
if(left_max[i]!=i && right_max[i]!=i){
sum=sum+min(A[left_max[i]],A[right_max[i]])-A[i];
}
}
return sum;
}
};
Trapping Rain Water
最新推荐文章于 2020-08-01 12:30:02 发布