leetcode系列(57)Trapping Rain Water
来源:互联网 发布:三星s8打不开淘宝 编辑:程序博客网 时间:2024/05/31 06:21
Given n non-negativeintegers representing an elevation map where the width of each bar is 1, computehow much water it is able to trap after raining.
Forexample,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
解答:这个题目可以解读为求每个柱子可以"顶"多少水(height),分析可发现每个柱子上能"顶"的水与它左边和右边最高柱子的最小的那个高度有关(最大值中求最小,是不是有点二份答案的味道),咋一看在遍历每个柱子的时候,需要左右各自搜索最大高度,时间复杂度O(n^2),但是其实不必的,首先用一个数组存储每个柱子的max_right_height,可以从右往左遍历并更新每个柱子的max_right_height,而max_left_height只需在从左到右遍历一边求每个柱子能顶多少水的时候一边更新,这里也给出了一些其它的解法,有点意思可以看下。
class Solution {public: int trap(vector<int>& height) { // the trap water of i is min(max height(0:i), max height(i+1:n)) - height[i] // use a vector to record max right height from the end to the first // traverse from left to right and update the current max left height of i // so traverse twic right to left and left to right vector<int> max_right(height.size(), 0); int ret = 0; int cur_max = 0; for (int i = static_cast<int>(height.size() - 1); i >= 0; --i) { max_right[i] = cur_max; cur_max = std::max(cur_max, height[i]); } cur_max = 0; for (size_t i = 0; i < height.size(); ++i) { int cur_height = std::min(cur_max, max_right[i]); if (cur_height > height[i]) { ret += cur_height - height[i]; } cur_max = std::max(cur_max, height[i]); } return ret; }};
0 0
- leetcode系列(57)Trapping Rain Water
- [leetcode刷题系列]Trapping Rain Water
- LeetCode: Trapping Rain Water
- LeetCode : Trapping Rain Water
- [LeetCode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [LeetCode]Trapping Rain Water
- LeetCode-Trapping Rain Water
- [leetcode] Trapping Rain Water
- [LeetCode] Trapping rain water
- Leetcode: Trapping Rain Water
- Leetcode:Trapping Rain Water
- [LeetCode] Trapping Rain Water
- <Leetcode>Trapping Rain Water
- Leetcode Trapping Rain Water
- leetcode Trapping Rain Water
- leetcode Trapping Rain Water
- hdoj 5523 Game 【细心题】
- HDOJ 1495 非常可乐(bfs)
- 【Little_things】事件驱动的带界面的Client/Server聊天小程序(java socket)
- 番茄工作法流程
- Activity的启动模式
- leetcode系列(57)Trapping Rain Water
- iOS--- 如何获得UIView的父控制器
- c3p0,Druid,Tomcat Jdbc Pool,dbcp2,proxoo数据源性能比较
- 欢迎使用CSDN-markdown编辑器
- Codeforces 592A PawnChess 【水题】
- 摘录
- 解决https需要验证问题
- PHP中CURL的CURLOPT_POSTFIELDS参数使用细节
- Codeforces 592B The Monster and the Squirrel 【规律题】