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
我们需要求出整个能蓄水多少。不妨考虑在位置 , 它能存储的水是多少。注意的一点是,当前位置的水量由左右侧最小值来决定。但一侧的高度我们需要维护最大值。
- 如果当前位置已经是某一侧的最大值了,此时显然存不了水
- 否则存储的容量则是:
点击查看代码
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; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程