题目链接:https://leetcode-cn.com/problems/trapping-rain-water/
Solution 1: Brute Force
对于每个位置cur(0,n-1),去寻找他左右两边的最高点,然后按照短板原则,取左右最高点的min,计算蓄水量,
r[i] = min(max(h[0:i+1]), max(h[i:n]))
ans = sum(r[i])
Time complexity: O(n^2)
Space complexity: O(1)
class Solution {
public:
int trap(vector<int>& height) {
const int n = height.size();
int ans = 0;
auto sit = cbegin(height);
auto eit = cend(height);
for (int i = 0; i < n; ++i) {
int l = *max_element(sit, sit + i + 1);
int r = *max_element(sit + i, eit);
ans += min(l, r) - height[i];
}
return ans;
}
};
Solution 2: DP
维护两个记录最大值的递增数组(l[i],r[i]),其中
l[i] := max(h[0:i+1])
r[i] := max(h[i:n])
ans = sum(min(l[i], r[i]) – h[i])
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
int trap(vector<int>& height) {
const int n = height.size();
vector<int> l(n);
vector<int> r(n);
int ans = 0;
for (int i = 0; i < n; ++i)
l[i] = i == 0 ? height[i] : max(l[i - 1], height[i]);
for (int i = n - 1; i >= 0; --i)
r[i] = i == n - 1 ? height[i] : max(r[i + 1], height[i]);
for (int i = 0; i < n; ++i)
ans += min(l[i], r[i]) - height[i];
return ans;
}
};
Solution 3: Two Pointers
双指针解决,l,r两个指针负责位置移动,max_l记录指针l的左边(位置0-l)的最大值,max_r记录r-n-1的最大值
Time complexity: O(n)
Space complexity: O(1)
class Solution {
public:
int trap(vector<int>& height) {
const int n = height.size();
if (n == 0) return 0;
int l = 0;
int r = n - 1;
int max_l = height[l];
int max_r = height[r];
int ans = 0;
while (l < r) {
if (max_l < max_r) {
ans += max_l - height[l];
max_l = max(max_l, height[++l]);
} else {
ans += max_r - height[r];
max_r = max(max_r, height[--r]);
}
}
return ans;
}
};
接雨水2题解:https://leetcode-cn.com/problems/trapping-rain-water-ii/