Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
trapping-rain-water.cpp 931 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-09-22 23:40 +08:00 . Update and rename trap.cpp to trapping-rain-water.cpp
// Time: O(n)
// Space: O(1)
class Solution {
public:
int trap(vector<int>& height) {
if (height.empty()) {
return 0;
}
int i = 0, j = height.size() - 1;
int left_height = height[0];
int right_height = height[height.size() - 1];
int trap = 0;
while (i < j) {
if (left_height < right_height) {
++i;
// Fill in the gap.
trap += max(0, left_height - height[i]);
// Update current max height from left.
left_height = max(left_height, height[i]);
}
else {
--j;
// Fill in the gap.
trap += max(0, right_height - height[j]);
// Update current max height from right.
right_height = max(right_height, height[j]);
}
}
return trap;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助