题目
代码(7.15 首刷调试看解析)
注意在求高度的时候,需要取最小值.
这个题和Leetcode 84. 柱状图中最大的矩形(⭐⭐⭐⭐⭐)的区别在于,不需要在前后加0,当然加了0也不会报错。
class Solution {
public:
int trap(vector<int>& height) {
stack<int> stk;
// height.insert(height.begin(), 0);
// height.push_back(0);
// stk.push(0);
int res = 0;
for(int i = 0; i < height.size(); i++) {
while(!stk.empty() && height[i] > height[stk.top()]) {
int mid = stk.top();
stk.pop();
if(!stk.empty()) {
int l = stk.top();
int w = i - l - 1;
res += w * (min(height[i], height[l]) - height[mid]);
}
}
stk.push(i);
}
return res;
}
};
代码(8.30 二刷自解)
class Solution {
public:
long long maxWater(vector<int>& arr) {
long long res = 0;
stack<int> sk;
for(int i = 0; i < arr.size(); i++) {
while(!sk.empty() && arr[sk.top()] < arr[i]) {
int mid = sk.top();
sk.pop();
if(!sk.empty()) {
int left = sk.top();
int height = min(arr[left], arr[i])-arr[mid];
res += height * (i-left-1);
}
}
sk.push(i);
}
return res;
}
};
另一种方法,最好都掌握。
class Solution {
public:
long long maxWater(vector<int>& arr) {
int n = arr.size();
vector<int> left_max(n), right_max(n);
left_max[0] = arr[0];
right_max[n-1] = arr[n-1];
for(int i = 1; i < n; i++) {
left_max[i] = max(left_max[i-1], arr[i]);
}
for(int i = n-2; i >= 0; i--) {
right_max[i] = max(right_max[i+1], arr[i]);
}
long long res = 0;
for(int i = 1; i < n-1; i++) {
res += min(right_max[i], left_max[i]) - arr[i];
}
return res;
}
};
代码(9.8 三刷自解)
class Solution {
public:
int trap(vector<int>& height) {
stack<int> sk;
int res = 0;
for(int i = 0; i < height.size(); i++) {
while(!sk.empty() && height[sk.top()] < height[i]) {
int mid = height[sk.top()];
sk.pop();
if(!sk.empty()) {
int l = sk.top();
res += (min(height[l], height[i])-mid)*(i-l-1);
// cout<<res<<" "<<height[l]<<" "<<mid<<" "<<height[i]<<endl;
}
}
sk.push(i);
}
return res;
}
};