题目
代码
按列来看,每次计算当前列可存储水量
int max(int a, int b) {
return a >= b ? a : b;
}
int min(int a, int b) {
return a <= b ? a : b;
}
//按列来计算,每次计算当前列可以存储多少水
int trap(int* height, int heightSize){
if (heightSize == 0 || heightSize == 1) return 0;
int max_left[heightSize], max_right[heightSize];
max_left[1] = height[0];
for (int i = 2; i < heightSize; i++) {
max_left[i] = max(max_left[i - 1], height[i - 1]);
}
max_right[heightSize - 2] = height[heightSize - 1];
for (int i = heightSize - 3; i >= 0; i--) {
max_right[i] = max(max_right[i + 1], height[i + 1]);
}
int sum = 0;
for (int i = 1; i < heightSize - 1; i++) {
int temp = min(max_left[i], max_right[i]);
if (temp > height[i]) {
sum += temp - height[i];
}
}
return sum;
}