DescriptionHintsSubmissionsDiscussSolution
Discuss Pick One
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.
class Solution {
public:
typedef vector<int>::size_type sz;
int trap(vector<int>& height) {
sz size = height.size();
if (size <= 2) return 0;
int ret = 0; // how many units of rain water trapped
// the max left height
sz max_lo;
if (height[0] > height[1])
max_lo = 0;
else
max_lo = 1;
for (sz i = 2; i < size; ++i) {
// 当height[i] > height[i - 1] 时才可以蓄水
if (height[i - 1] < height[i]) {
int base = height[i - 1];
// for 循环是因为 height[i] 可能与多栏蓄水如 【4 2 0 3】
// 当 j 小于 max_lo 时说明左边没有更高的栏所以不用计算
for (int j = i - 2; j >= int(max_lo); --j){
int h = 0;
// 当 height[j] > base 时说明该栏与height[i] 之间可以蓄水
if (height[j] > base) {
h = min(height[j], height[i]);
ret += (i - j - 1) * (h - base);
base = h;
}
if (height[j] >= height[i])
break;
}
if (height[i] >= height[max_lo]) {
max_lo = i;
}
}
}
return ret;
}
};
参考后
class Solution {
public:
typedef vector<int>::size_type sz;
int trap(vector<int>& height) {
sz size = height.size();
if (size == 0) return 0;
sz lo = 0;
sz hi = size - 1;
int ret = 0;
while (lo < hi) {
while (height[lo] <= height[hi]) {
sz i = lo + 1;
while (height[i] < height[lo]) {
ret += height[lo] - height[i];
cout << ret << "i" << endl;
++i;
}
lo = i;
if (lo == hi) return ret;
}
while (height[lo] > height[hi]) {
sz i = hi - 1;
while (height[i] < height[hi]) {
ret += height[hi] - height[i];
--i;
}
hi = i;
if (lo == hi) return ret;
}
}
return ret;
}
};