leetcode题集——trapping-rain-water
来源:互联网 发布:java小软件源代码 编辑:程序博客网 时间:2024/06/13 14:48
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], return6.
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!
解析:使用双指针法。分别从数组两边开始遍历,当leftmax>rightmax时,可以求出right=n-2位置的水量;反之,当leftmax<rightmax时,可以求出left=1位置的水量。
循环条件为left<=right。
class Solution {public: int max(int a,int b) { return a>b?a:b; } int trap(int A[], int n) { if(A==NULL||n<3) return 0; int sum; int leftmax=A[0]; int rightmax=A[n-1]; int l=1; int r=n-2; while(l<=r) { if(leftmax<rightmax) {//左侧最小值比右侧值小 sum+=max(0,leftmax-A[l]); leftmax=max(leftmax,A[l++]); } else { sum+=max(0,rightmax-A[r]); rightmax=max(rightmax,A[r--]); } } return sum; }};
0 0
- leetcode题集——trapping-rain-water
- 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 : 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
- RxJava(二)歪论
- final关键字
- iOS开发Xcode的图片管理(Images.xcassets)
- iOS中NSString类型数据保留两位小数
- Revit二次开发手记【1】
- leetcode题集——trapping-rain-water
- android 虚拟键适配PopupWindow显示位置
- OSG RTT 渲染到纹理
- 安装配置Zookeeper
- iOS7.2 如何设置导航,不使用系统默认跳转的ViewController
- 文章标题
- 路径问题系列之HDU1312 Red and Black(DFS)
- Meta http-equiv属性详解(转)
- react学习