xinyu04

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

LeetCode 42 Trapping Rain Water 双指针+思维

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Solution

我们需要求出整个能蓄水多少。不妨考虑在位置 i, 它能存储的水是多少。注意的一点是,当前位置的水量由左右侧最小值来决定。但一侧的高度我们需要维护最大值。

  • 如果当前位置已经是某一侧的最大值了,此时显然存不了水
  • 否则存储的容量则是: min(lmaxrmax)h
点击查看代码
class Solution {
private:
int ans=0;
int lmax[20003];
int rmax[20003];
public:
int trap(vector<int>& height) {
int n = height.size();
lmax[0] = height[0];
rmax[n-1] = height[n-1];
for(int i=1;i<n;i++){
lmax[i] = max(lmax[i-1], height[i]);
}
for(int i=n-2;i>=0;i--){
rmax[i] = max(rmax[i+1], height[i]);
}
for(int i=0;i<n;i++){
ans+= min(lmax[i], rmax[i])-height[i];
}
return ans;
}
};

posted on   Blackzxy  阅读(8)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示