我的题解博客:欢迎大家访问,点击这里!
三次扫描
纵向计算!
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
if(n == 0) return 0;
vector<int> left_max(n), right_max(n);
left_max[0] = height[0];
for(int i = 1; i < n; i ++) left_max[i] = max(left_max[i - 1], height[i]);
right_max[n - 1] = height[n - 1];
for(int i = n - 2; i >= 0; i --) right_max[i] = max(right_max[i + 1], height[i]);
int res = 0;
for(int i = 0; i < n; i ++) res += min(left_max[i], right_max[i]) - height[i];
return res;
}
};
单调栈
横向计算!
class Solution {
public:
stack<int> stk;
int trap(vector<int>& height) {
int res = 0;
for(int i = 0; i < height.size(); i ++){
while(stk.size() && height[stk.top()] <= height[i]){
int last = stk.top(); stk.pop();
if(stk.empty()) break;
res += (min(height[stk.top()], height[i]) - height[last]) * (i - stk.top() - 1);
}
stk.push(i);
}
return res;
}
};
双指针(最优)
纵向计算!
class Solution {
public:
stack<int> stk;
int trap(vector<int>& height) {
int n = height.size();
if(!n) return 0;
int left_max = height[0], right_max = height[n - 1];
int l = 0, r = n - 1, res = 0;
while(l < r){
if(left_max < right_max) {
res += left_max - height[l ++];
left_max = max(left_max, height[l]);
}else {
res += right_max - height[r --];
right_max = max(right_max, height[r]);
}
}
return res;
}
};