题目大意:
一个数组表示各个点的高度,问能存储多少水。
思路:
对每个点求出它左面和右面的最大值,就可以求出当前点能存储的单元。
代码:
class Solution {
public:
int trap(vector<int>& height) {
if (height.empty()) return 0;
int n = height.size();
vector<int> left(n, 0);
vector<int> right(n, 0);
// init
left[0] = 0;
right[n-1] = 0;
// left
int left_max = height[0];
for (int i=1; i<n; ++i) {
left[i] = left_max;
left_max = max(left_max, height[i]);
}
int right_max = height[n-1];
for (int i=n-2; i>=0; --i) {
right[i] = right_max;
right_max = max(right_max, height[i]);
}
int ans = 0;
for (int i=1; i<n-1; ++i) {
// cout << left[i] << " " << right[i] << "==\n";
int temp = min(left[i], right[i]) - height[i];
ans += max(temp, 0);
}
return ans;
}
};
为什么就是不能自己想出解题思路来呢。。。。
上午可能是头发太油了心情不好,加上没睡好脑壳痛。
多看论文,继续做kaggle。
成也是你,败也是你。
加油鸭。