Leetcode: Trapping Rain Water
来源:互联网 发布:对外经济贸易大学知乎 编辑:程序博客网 时间:2024/06/06 05:34
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
.
Scan the integers from left to right and store the maximum trapped water from left to that bar in an array. Then scan from right to left and again store the maximum trapped water from right to that bar. For each bar, the maximum trapped water from both side is the minimum value from left and right side. Add the maximum values of each bar and get the result. O(n) time and O(n) space.
public class Solution { public int trap(int[] A) { if (A == null || A.length == 0) { return 0; } int[] max = new int[A.length]; max[0] = 0; int left = A[0]; for (int i = 1; i < A.length; i++) { max[i] = left > A[i] ? (left - A[i]) : 0; left = Math.max(left, A[i]); } int res = 0; int right = A[A.length - 1]; for (int i = A.length - 2; i >= 0; i--) { int cur = right > A[i] ? (right - A[i]) : 0; right = Math.max(right, A[i]); res += Math.min(cur, max[i]); } return res; }}
0 0
- 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
- Leetcode Trapping Rain Water
- leetcode Trapping Rain Water
- leetcode Trapping Rain Water
- LeetCode Trapping Rain Water
- LeetCode | Trapping Rain Water
- Word Break II
- 汇编器源码剖析
- emacs在mac上使用
- 百度实习面试
- LeetCode——Count and Say
- Leetcode: Trapping Rain Water
- git reset-----git 本地仓库回退
- 锐捷5.20代理检测之ACK响应报文检测
- c和指针 03
- misc_register、 register_chrdev 的区别总结
- JSON入门
- 修改wamp中mysql的默认密码
- solaris 系统信息查看
- Haproxy、Keepalived双主高可用负载均衡