第一周:[leetcode] 42. Trapping Rain Water
2017-02-26 11:34
369 查看
题目链接:链接
question: Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
简而言之,该题是计算非负数组形成的凹槽所能承载的水量;
通过观察得知,数组的载水量由两值形成的局部(凹槽)的最低点决定,因此,计算总在水量应是从数组局部较低点向较高点扫描。将整个数组视为整体,维护left=0和right=height.size()-1两个index,通过比较取较小值向高点移动,直到left == right停止,计算累计在水量。
c++实现如下:
通过学习solution,发现更加简便的计算方法:
维护level,从第0层开始由两边向中扫描,累积在水量。直至l
question: Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
简而言之,该题是计算非负数组形成的凹槽所能承载的水量;
通过观察得知,数组的载水量由两值形成的局部(凹槽)的最低点决定,因此,计算总在水量应是从数组局部较低点向较高点扫描。将整个数组视为整体,维护left=0和right=height.size()-1两个index,通过比较取较小值向高点移动,直到left == right停止,计算累计在水量。
c++实现如下:
int trap(vector<int>& height) { int front = 0; int back = height.size()-1; int res = 0; while(front < back){ //取两者较小值向高点移动 if(height[front] < height[back]){ int f = height[front]; while(height[front] <= f && front < back){ res += f - height[front]; front++; } } else{ int b = height[back]; while(height[back] <= b && front < back){ res += b - height[back]; back--; } } } return res; }
通过学习solution,发现更加简便的计算方法:
维护level,从第0层开始由两边向中扫描,累积在水量。直至l
int trap(vector<int>& height) { int l = 0, r = height.size()-1, level = 0, water = 0; while (l < r) { int lower = height[height[l] < height[r] ? l++ : r--]; level = max(level, lower); water += level - lower; } return water; }
相关文章推荐
- leetcode题解-42. Trapping Rain Water
- [array] leetcode - 42. Trapping Rain Water - Hard
- LeetCode: 42. Trapping Rain Water
- [Leetcode] 42. Trapping Rain Water 解题报告
- 42. Trapping Rain Water leetcode Python 2016 new season
- LeetCode 42. Trapping Rain Water
- LeetCode- 42. Trapping Rain Water (JAVA)收集雨水
- leetcode.array--42. Trapping Rain Water
- [leetcode 42. Trapping Rain Water] Hard | Week 1
- [LeetCode]42. Trapping Rain Water
- LeetCode --- 42. Trapping Rain Water
- Leetcode: 42. Trapping Rain Water
- 面试算法——双指针的应用leetcode 42. Trapping Rain Water
- [leetcode] 42. Trapping Rain Water 解题报告
- Leetcode 42. Trapping Rain Water (Hard) (cpp)
- LeetCode 42. Trapping Rain Water(收集雨水Ⅰ)
- [LeetCode] 42. Trapping Rain Water 收集雨水
- LeetCode 42. Trapping Rain Water
- 【LeetCode】42. Trapping Rain Water
- ***LeetCode 42. Trapping Rain Water