Trapping Rain Water
2014-08-16 10:13
281 查看
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
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!
One Pass and O(1) space.
One Pass and O(1) space.
The idea is search the array from two sides to middle, keep tracking the second highest value and use it to minus the value of A[i] the answer is the capacity of current point.
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!
public class Solution { public int trap(int[] A) { if(A==null || A.length<=2) return 0; int left=0,right=A.length-1; int all=0,block=0,curr=0; while(left<=right){ int level=Math.min(A[left],A[right]); if(level>curr){ all+=(level-curr)*(right-left+1); curr=level; } if(A[left]<A[right]){ block+=A[left++]; } else{ block+=A[right--]; } } return all-block; } }
One Pass and O(1) space.
class Solution { public: int trap(int A[], int n) { if(n==0) return 0; int l = 0, r = n-1,block = 0,all = 0,curlevel = 0; while(l<=r) { if(min(A[l],A[r])>curlevel) { all += (min(A[l],A[r])-curlevel)*(r-l+1); curlevel = min(A[l],A[r]); } if(A[l]<A[r]) block += A[l++]; else block += A[r--]; } return all-block; } };
One Pass and O(1) space.
The idea is search the array from two sides to middle, keep tracking the second highest value and use it to minus the value of A[i] the answer is the capacity of current point.
public class Solution { public int trap(int[] A) { int secHight = 0; int left = 0; int right = A.length - 1; int area = 0; while (left < right) { if (A[left] < A[right]) { secHight = Math.max(A[left], secHight); area += secHight - A[left]; left++; } else { secHight = Math.max(A[right], secHight); area += secHight - A[right]; right--; } } return area; } }
相关文章推荐
- leetcode: Trapping Rain Water
- leetcode-042:Trapping Rain Water
- Trapping Rain Water
- LeetCode: Trapping Rain Water [041]
- LeetCode Trapping Rain Water
- [leetcode] Trapping Rain Water
- 【线性扫描ijk_贪心】candy 最少蛋糕分配、Trapping Rain water
- 2.1.15 Trapping Rain Water
- Leetcode Trapping Rain Water
- leetcode Trapping Rain Water
- Trapping Rain Water
- Java for LeetCode 042 Trapping Rain Water
- Leetcode42 Trapping Rain Water
- LeetCode(42)Trapping Rain Water
- Trapping Rain Water
- 42. Trapping Rain Water
- leetcode42_Trapping Rain Water
- 42. Trapping Rain Water
- Leetcode刷题记——Trapping Rain Water(捕获雨水)
- Trapping Rain Water(第八周)