LeetCode题解——Trapping Rain Water
来源:互联网 发布:laravel mac 环境 编辑:程序博客网 时间:2024/06/05 00:19
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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
这道题和container with most water 有点类似,但是这道题更难一点;分析题目可看出,随意给定一组数字,可能形成很多个"坑",那么是否可以每次计算出一个坑中的水,最后将其相加得到最终结果。
用递归是容易做到的,每次找出两个最高的bar,然后计算这两个bar之间的水量,再分别在其左边和右边递归的进行寻找。
class Solution {public: int trap(vector<int>& height) {//用递归可以实现 if(height.size()<3) return 0; int maxidxI=0,maxidxJ=height.size()-1; int temp,water = 0;for(int i=1;i<height.size()-1;i++){if(height[i]>height[maxidxI])maxidxI = i;}for(int i =height.size()-1;i>=0;i--){ if(height[i]>height[maxidxJ] && i!=maxidxI) maxidxJ = i;}if(maxidxI>maxidxJ){int t = maxidxI;maxidxI =maxidxJ;maxidxJ =t;} temp =0; for(int m = maxidxI+1 ; m<= maxidxJ-1; m++) temp+= height[m]; water+=(height[maxidxI]>height[maxidxJ]?height[maxidxJ]:height[maxidxI])*(maxidxJ - maxidxI -1) - temp; vector<int> l(height.begin(),height.begin()+maxidxI+1),r(height.begin()+maxidxJ,height.end()); return water+trap(l)+trap(r); }};
0 0
- LeetCode题解——Trapping Rain Water
- LeetCode —— Trapping Rain Water
- LeetCode——Trapping Rain Water
- leetcode 042 —— Trapping Rain Water
- Leetcode—— trapping-rain-water
- leetcode题集——trapping-rain-water
- LeetCode——Trapping Rain Water
- LeetCode 题解(14):Trapping Rain Water
- leetcode题解-42. Trapping Rain Water
- leetcode题解-42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water 题解
- 题解: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
- [Mark]分布式存储必读论文
- Mac版QQ 无法截图处理方法
- XX下载器分析过程
- Direct-X学习笔记--三维摄像机
- tableau desktop(三)--构建数据视图(二)
- LeetCode题解——Trapping Rain Water
- 树(基本概念及存储结构)
- PHP:快速排序法
- 欢迎使用CSDN-markdown编辑器
- java面向对象的思想
- swing 将system.out输出的信息重定向到JTEXTAREA
- 进程状态
- LeetCode题解-Best Time to Buy and Sell Stock III
- 认识shell