LeetCode 111 Trapping Rain Water
2014-10-31 11:07
363 查看
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.
分析:
对于每一格A[i],计算左边的最高沿left[i],再计算右边的最高沿right[i],根据木桶原理,这一格能存的水就是:
vol = min{left[i], right[i]} - A[i] > 0 ? min{left[i], right[i]} - A[i] : 0;
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
分析:
对于每一格A[i],计算左边的最高沿left[i],再计算右边的最高沿right[i],根据木桶原理,这一格能存的水就是:
vol = min{left[i], right[i]} - A[i] > 0 ? min{left[i], right[i]} - A[i] : 0;
public class Solution { public int trap(int[] A) { if(A==null || A.length==0) return 0; int[] left = new int[A.length]; int[] right = new int[A.length]; //计算左边最大 int max = A[0]; for(int i=0; i<A.length; i++){ if(A[i] <= max){ left[i] = max; }else{ left[i] = A[i]; max = A[i]; } } //计算右边最大 max=A[A.length-1]; for(int i=A.length-1; i>=0; i--){ if(A[i] <= max){ right[i] = max; }else{ right[i] = A[i]; max = A[i]; } } //计算储水,0和A.length-1位置不算 int vol = 0; for(int i=1; i<A.length-1; i++){ //左右沿取最低 int height = Math.min(left[i], right[i]); if(height > A[i]){ vol += height-A[i]; } } return vol; } }
相关文章推荐
- [LeetCode111]Trapping Rain Water
- [LeetCode] Trapping Rain Water
- LeetCode--Trapping Rain Water
- leetcode hard模式专杀之42. Trapping Rain Water
- [leetcode] Trapping Rain Water
- [leetcode] Trapping Rain Water
- 【LeetCode with Python】 Trapping Rain Water
- [leetcode]Trapping Rain Water
- LeetCode(42)--Trapping Rain Water
- LeetCode – Refresh – Trapping Rain Water
- [leetcode] Trapping Rain Water
- leetcode Trapping Rain Water
- LeetCode —— Trapping Rain Water
- [Leetcode] Trapping Rain Water
- Leetcode NO.42 Trapping Rain Water
- leetcode Trapping Rain Water
- 【leetcode】Trapping Rain Water
- LeetCode Online Judge 题目C# 练习 - Trapping Rain Water
- [leetcode]Trapping Rain Water
- LeetCode-Trapping Rain Water