42. 接雨水

 1 //自底向上层层叠加
 2 class Solution 
 3 {
 4 public:
 5     int trap(vector<int>& height) 
 6     {
 7         int res = 0;
 8         stack<int> stk;
 9 
10         for(int i = 0;i < height.size();i ++)
11         {
12             int last = 0;
13             while(stk.size() && height[stk.top()] <= height[i])
14             {
15                 int t = stk.top();
16                 stk.pop();
17 
18                 res += (i - t - 1) * (height[t] - last);
19                 cout << res << " ";
20                 last = height[t];
21             }
22 
23             if(stk.size())
24             {
25                 res += (i - stk.top() - 1) * (height[i] - last);
26             }
27             cout << res << " ";
28             stk.push(i);
29             cout << endl;
30         }
31         return res;
32     }
33 }; 

 

 1 class Solution 
 2 {
 3 public:
 4     int trap(vector<int>& height) 
 5     {
 6         if (height.empty()) return 0;
 7         int n = height.size();
 8         int ans = 0;
 9         // 数组充当备忘录
10         vector<int> l_max(n), r_max(n);
11 
12         // 初始化 base case
13         l_max[0] = height[0];
14         r_max[n - 1] = height[n - 1];
15 
16         // 从左向右计算 l_max
17         for (int i = 1; i < n; i++)
18             l_max[i] = max(height[i], l_max[i - 1]);
19             
20         // 从右向左计算 r_max
21         for (int i = n - 2; i >= 0; i--) 
22             r_max[i] = max(height[i], r_max[i + 1]);
23 
24         // 计算答案
25         for (int i = 1; i < n - 1; i++) 
26             ans += min(l_max[i], r_max[i]) - height[i];
27         return ans;
28     }
29 };

 

 1 class Solution 
 2 {
 3 public:
 4     int trap(vector<int>& height) 
 5     {
 6         if (height.empty()) return 0;
 7         int n = height.size();
 8         int left = 0, right = n - 1;
 9         int ans = 0;
10 
11         int l_max = height[0];
12         int r_max = height[n - 1];
13 
14         while (left <= right) 
15         {
16             l_max = max(l_max, height[left]);
17             r_max = max(r_max, height[right]);
18 
19             // ans += min(l_max, r_max) - height[i]
20             if (l_max < r_max) 
21             {
22                 ans += l_max - height[left];
23                 left++; 
24             } 
25             else 
26             {
27                 ans += r_max - height[right];
28                 right--;
29             }
30         }
31         return ans;
32     }
33 };

 

posted @ 2020-04-08 16:04  Jinxiaobo0509  阅读(111)  评论(0)    收藏  举报