LeetCode:Trapping Rain Water(装雨水问题)
来源:互联网 发布:picasa软件官方下载 编辑:程序博客网 时间:2024/06/11 22:35
原题: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.
两种方法的时间复杂度均为O(n),但方法1需要额外维护一个堆栈。
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!
计算柱形图内最多能装多少雨水。
1.首先可以想到用堆栈。如果当前高度比堆栈顶端的高度小,则当前下标进栈,且累加积水面积;如果当前高度比堆栈顶端的高度大,则出栈,且累加积水面积,如此循环。
堆栈里始终维护的是高度依次递减的柱形。所以可以考虑下图的三种情况。
(1)当前高度比堆栈内高度小,直接进栈,且累加黄色部分面积。
(2)当前高度大于堆栈内高度,则首先累加黄色部分面积,退栈,计算绿色部分面积,进栈。这个过程需要保存已经处理过的黄色部分的高度lastHeight。
class Solution {public: int trap(int A[], int n) { if(A==NULL || n<=2)return 0;stack<int> s;s.push(0);int i=1,sum = 0;int lastHeight = 0;while(i<n){lastHeight = 0;while(A[i]>=A[s.top()]){sum += (i-s.top()-1)*(A[s.top()]-lastHeight);lastHeight = A[s.top()];s.pop();if(s.empty()){s.push(i++);lastHeight = 0;}}sum += (i-s.top()-1)*(A[i]-lastHeight);s.push(i++);}return sum; }};2. 双指针方法。首尾各一个指针向中间移动,移动的过程中累加面积。
class Solution {public: int trap(int A[], int n) { if(A==NULL || n<=2)return 0;int sum = 0;int left = 0, right = n-1;int maxLeft = A[0], maxRight = A[n-1];while(left<right){if(A[left]<A[right]){if(maxLeft>A[left])sum += maxLeft-A[left++];elsemaxLeft = A[left++];}else{if(maxRight>A[right])sum += maxRight-A[right--];elsemaxRight = A[right--];}}return sum; }};上述的maxLeft和maxRight可以只用一个值。
class Solution {public: int trap(int A[], int n) { if(A==NULL || n<=2)return 0;int sum = 0;int left = 0, right = n-1;int max = 0;while(left<right){if(A[left]<A[right]){if(max>A[left])sum += max-A[left++];elsemax = A[left++];}else{if(max>A[right])sum += max-A[right--];elsemax = A[right--];}}return sum; }};
两种方法的时间复杂度均为O(n),但方法1需要额外维护一个堆栈。
0 0
- LeetCode:Trapping Rain Water(装雨水问题)
- LeetCode 42. Trapping Rain Water(装雨水)
- [LeetCode] Trapping Rain Water 搜集雨水
- Trapping Rain Water(捕获雨水)
- LeetCode Trapping Rain Water等雨水的凹槽容量
- LeetCode - Trapping Rain Water 等雨水的凹槽容量
- LeetCode OJ 之 Trapping Rain Water (“收集”雨水)
- Leetcode #42. Trapping Rain Water 雨水收集 解题报告
- LeetCode------42. Trapping Rain Water(捕获雨水量)
- Leetcode刷题记——Trapping Rain Water(捕获雨水)
- LeetCode-42. Trapping Rain Water (JAVA)收集雨水
- LeetCode--Trapping Rain Water(捕获雨水)Python
- Trapping Rain Water 捕获最多的雨水
- **[Lintcode]Trapping Rain Water 接雨水
- 接雨水最大面积Trapping Rain Water
- Trapping Rain Water 接雨水 python
- 42. Trapping Rain Water(捕获雨水)
- LeetCode: Trapping Rain Water
- POJ 1979 Red and Black (DFS)
- printf和cout右向左求值
- android ListView和GridView拖拽移位具体实现及拓展
- Domino Calendar REST API性能调优 之 Server配置篇
- 帧动画以及AnimationDrawable的使用
- LeetCode:Trapping Rain Water(装雨水问题)
- RHEL7.0 DHCP+TFTP+SYSLINUX+FTP+KICKSTART自动安装
- 我
- 开源播放器ijkplayer-android编译
- HTTP协议详解
- 励志
- 如何让Flash不遮挡HTML元素
- 如何用Avro在内存中实现序列化 和反序列化
- js调用打印机打印