【双指针】接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨

示例 1:

复制代码
 输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
 输出:6
 解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 

示例 2:

复制代码
 输入:height = [4,2,0,3,2,5]
 输出:9
复制代码
 class Solution {
 public:
     int trap(vector<int>& height) {
         int sum = 0;
         for(int i = 0;i<height.size();i++){
             // 第一个柱子和最后一个柱子不接雨水
             if (i == 0 || i == height.size() - 1) continue;
             int rHeight = height[i];//右边高的
             int lHeight = height[i];//左边高的
             for(int r = i+1;r<height.size();r++){
                 if(rHeight<height[r]){
                     rHeight = height[r];
                 }
             }
             for(int l = i-1;l>=0;l--){
                 if(height[l]>lHeight) lHeight = height[l];
             }
             int h = min(lHeight,rHeight) - height[i];
             if(h>0) sum+=h;
         }
         return sum;
 ​
     }
 };
 ​
 //宽度是1  然后给的数组就是代表柱子的高度 所以说看例子就是看他的凹槽可以得到多少水
 ​

很遗憾双指针超时了

复制代码
 class Solution {
 public:
     int trap(vector<int>& height) {
         int ans = 0;
         int left = 0, right = height.size() - 1;
         int leftMax = 0, rightMax = 0;
         while (left < right) {
             leftMax = max(leftMax, height[left]);
             rightMax = max(rightMax, height[right]);
             if (height[left] < height[right]) {
                 ans += leftMax - height[left];
                 ++left;
             } else {
                 ans += rightMax - height[right];
                 --right;
             }
         }
         return ans;
     }
 };
 ​
 ​
相关推荐
爱coding的橙子4 分钟前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
慢慢慢时光6 分钟前
leetcode sql50题
算法·leetcode·职场和发展
pay顿7 分钟前
力扣LeetBook数组和字符串--二维数组
算法·leetcode
精神小伙mqpm9 分钟前
leetcode78. 子集
算法·深度优先
岁忧9 分钟前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
Tisfy11 分钟前
LeetCode 2434.使用机器人打印字典序最小的字符串:贪心(栈)——清晰题解
leetcode·机器人·字符串·题解·贪心·
dying_man12 分钟前
LeetCode--18.四数之和
算法·leetcode
知识漫步38 分钟前
代码随想录算法训练营第60期第五十九天打卡
算法
分形数据1 小时前
在Mathematica中实现Newton-Raphson迭代的收敛时间算法(一般三次多项式)
算法·mathematica·复分析
鑫鑫向栄1 小时前
[蓝桥杯]解谜游戏
数据结构·c++·算法·职场和发展·蓝桥杯