【双指针】接雨水

给定 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;
     }
 };
 ​
 ​
相关推荐
C雨后彩虹2 分钟前
优雅子数组
java·数据结构·算法·华为·面试
漫随流水8 分钟前
leetcode回溯算法(46.全排列)
数据结构·算法·leetcode·回溯算法
We་ct11 分钟前
LeetCode 68. 文本左右对齐:贪心算法的两种实现与深度解析
前端·算法·leetcode·typescript
努力学算法的蒟蒻14 分钟前
day67(1.26)——leetcode面试经典150
算法·leetcode·面试
iAkuya16 分钟前
(leetcode) 力扣100 52腐烂的橘子(BFS)
算法·leetcode·宽度优先
老鼠只爱大米20 分钟前
LeetCode经典算法面试题 #148:排序链表(插入、归并、快速等五种实现方案解析)
算法·leetcode·链表·插入排序·归并排序·快速排序·链表排序
木井巳33 分钟前
【递归算法】计算布尔二叉树的值
java·算法·leetcode·深度优先
睡一觉就好了。1 小时前
直接选择排序
数据结构·算法·排序算法
哈哈不让取名字1 小时前
分布式日志系统实现
开发语言·c++·算法