Trapping Rain Water
来源:互联网 发布:java字符串里的大括号 编辑:程序博客网 时间:2024/06/05 19:41
Q:
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!
Solution:
public class Solution { public int trap(int[] A) { if (A == null || A.length == 0) return 0; Stack<Integer> stack = new Stack<Integer>(); Stack<Integer> width = new Stack<Integer>(); int start = 0; while (start < A.length && A[start] == 0) start++; if (start < A.length) { stack.push(A[start]); width.push(1); } int trap = 0; for (int i = start+1; i < A.length; i++) { if (A[i] <= stack.peek()) { stack.push(A[i]); width.push(1); } else { int w = 0; while (!stack.isEmpty() && stack.peek() <= A[i]) { int height = stack.pop(); w += width.pop(); if (!stack.isEmpty()) trap += (Math.min(stack.peek(), A[i]) - height) * w; } stack.push(A[i]); width.push(w+1); } } return trap; }}
0 0
- LeetCode: Trapping Rain Water
- LeetCode : Trapping Rain Water
- Trapping Rain Water
- [LeetCode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- Trapping Rain Water
- Trapping Rain Water
- [LeetCode]Trapping Rain Water
- Trapping Rain Water
- Trapping Rain Water
- LeetCode-Trapping Rain Water
- Trapping Rain Water
- [leetcode] Trapping Rain Water
- Trapping Rain Water
- [LeetCode] Trapping rain water
- Leetcode: Trapping Rain Water
- 38 - Trapping Rain Water
- 获取Eclipse及插件路径汇总
- html5标签
- CALayer_超经典的阐述原理
- Visual Studio与C#编程十个实用技巧
- Linux I2C 总线浅析
- Trapping Rain Water
- 指针函数和函数指针
- 关于新浪博客输入javascript语句会自动屏蔽的解决办法
- 好东西,转载园子的博文。关于值类型和引用类型区别,讲的很清晰
- 10个C#编程和Visual Studio使用技巧
- BC#20 LINES
- 四十三 毕设(下)我在软件园的那些日子里
- HDU 2069 Coin Change
- USB枚举详细过程剖析