[LeetCode] 42. Trapping Rain Water
题目
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
In this case, 6 units of rain water (blue section) are being trapped.
思路
第 i 个位置上的水量为 min(i左边height最大值,i右边height最大值) - height[i]
最大值可以提前算出来。
这题还有单调栈和双指针法,有空再看。
代码
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int l[n+1], r[n+1];
int maxx = 0;
for (int i = 0; i < n; i++) {
maxx = max(maxx, height[i]);
l[i] = maxx;
}
maxx = 0;
int ans = 0;
for (int i = n - 1; i >= 0; i--) {
maxx = max(maxx, height[i]);
r[i] = maxx;
ans += min(l[i], r[i]) - height[i];
}
return ans;
}
};
吐槽: 我一开始想成单调栈了,受到之前做过题的影响.
有空找一找单调栈的题,看看区别。
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int l[n+1], r[n+1];
for (int i = 0; i < n; i++) {
l[i] = r[i] = i;
}
for (int i = 1; i < n; i++) {
while (l[i] > 0 && height[l[i]] <= height[l[l[i]-1]]) l[i] = l[l[i]-1];
}
for (int i = n -2; i >= 0; i--) {
while (r[i] < n-1 && height[r[i]] <= height[r[r[i]+1]]) r[i] = r[r[i]+1];
}
int ans = 0;
for (int i = 0; i < n; i++) {
ans += min(height[l[i]], height[r[i]]) - height[i];
}
return ans;
}
};