forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main4.cpp
57 lines (44 loc) · 1.23 KB
/
main4.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/// Source : https://leetcode.com/problems/trapping-rain-water/description/
/// Author : liuyubobobo
/// Time : 2018-09-16
#include <iostream>
#include <vector>
using namespace std;
/// Using Stack
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
int trap(vector<int>& height) {
if(height.size() <= 2)
return 0;
vector<int> stack;
int res = 0;
for(int i = 0; i < height.size(); i ++){
while(!stack.empty() && height[i] > height[stack.back()]){
int cur = stack.back();
stack.pop_back();
if(stack.empty())
break;
int dis = i - stack.back() - 1;
int h = min(height[stack.back()], height[i]) - height[cur];
res += h * dis;
}
stack.push_back(i);
}
return res;
}
};
int main() {
vector<int> height1 = {0,1,0,2,1,0,1,3,2,1,2,1};
cout << Solution().trap(height1) << endl;
// 6
vector<int> height2 = {4,2,3};
cout << Solution().trap(height2) << endl;
// 1
vector<int> height3 = {4, 2, 0, 3, 2, 5};
cout << Solution().trap(height3) << endl;
// 9
return 0;
}