Skip to content

Commit d8bf190

Browse files
committed
Progress: 17/150 - Method 2 Done
1 parent 09be7c9 commit d8bf190

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

cpp/017#TrappingRainWater2.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// 动态规划
2+
// Time Complexity: O(n)
3+
// Space Complexity: O(n)
4+
5+
# include <iostream>
6+
# include <vector>
7+
using namespace std;
8+
9+
10+
class Solution {
11+
public:
12+
int trap(vector<int>& height) {
13+
int sum = 0;
14+
// (height.size(), 0) means (size, initial value)
15+
vector<int> max_left(height.size(), 0);
16+
vector<int> max_right(height.size(), 0);
17+
18+
// max_left [i] = Max(max_left [i-1],height[i-1])。它前边的墙的左边的最高高度和它前边的墙的高度选一个较大的,就是当前列左边最高的墙了
19+
for (int i = 1; i < height.size() - 1; i++) {
20+
max_left[i] = max(max_left[i - 1], height[i - 1]);
21+
}
22+
23+
// max_right[i] = Max(max_right[i+1],height[i+1]) 。它后边的墙的右边的最高高度和它后边的墙的高度选一个较大的,就是当前列右边最高的墙了
24+
for (int i = height.size() - 2; i >= 0; i--) {
25+
max_right[i] = max(max_right[i + 1], height[i + 1]);
26+
}
27+
28+
// 这样,我们再利用解法一的算法,就不用在 for 循环里每次重新遍历一次求 max_left 和 max_right 了。
29+
for (int i = 1; i < height.size() - 1; i++) {
30+
int min_val = min(max_left[i], max_right[i]);
31+
if (min_val > height[i]) {
32+
sum += (min_val - height[i]);
33+
}
34+
}
35+
return sum;
36+
}
37+
};
38+
39+
int main() {
40+
Solution s;
41+
vector<int> height = {0,1,0,2,1,0,1,3,2,1,2,1};
42+
cout << s.trap(height) << endl;
43+
return 0;
44+
}

0 commit comments

Comments
 (0)