Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
int trap(vector<int>& height) {
int sz = size(height);
vector<int> l(sz);
vector<int> r(sz);
for (int i = 1; i < sz; ++i) {
l[i] = max(l[i - 1], height[i - 1]); // height[i] 左侧最大高度
}
for (int i = sz - 2; i >= 0; --i) {
r[i] = max(r[i + 1], height[i + 1]); // height[i] 右侧最大高度
}
int res = 0;
for (int i = 0; i < sz; i++) {
res += max(0, min(l[i], r[i]) - height[i]);
}
return res;
}
};
class Solution {
public:
int trap(vector<int>& height) {
int l = 0;
int r = size(height) - 1;
int mx = 0;
int res = 0;
while (l < r) {
if (height[l] < height[r]) {
mx = max(mx, height[l]);
res += mx - height[l];
++l;
} else {
mx = max(mx, height[r]);
res += mx - height[r];
--r;
}
}
return res;
}
};