LeetCode OJ Trapping Rain Water
2015-03-21 09:28
337 查看
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!
思路是这样的:
我们每次只考虑一单位宽度的位置能放多少水。对于某个位置来说,我们先找到它左边的最高点(有可能就是它本身),再找到它右边的最高点(有可能是它本身),然后,这个单位上最多能放min(leftMax, rightMax) - A[i],及两边最大值的较小值减去它的高度,道理由上图显而易见。
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!
思路是这样的:
我们每次只考虑一单位宽度的位置能放多少水。对于某个位置来说,我们先找到它左边的最高点(有可能就是它本身),再找到它右边的最高点(有可能是它本身),然后,这个单位上最多能放min(leftMax, rightMax) - A[i],及两边最大值的较小值减去它的高度,道理由上图显而易见。
class Solution { public: int trap(int A[], int n) { int * lmax = new int ; int * rmax = new int ; for (int i = 0, Max = -1; i < n; i++) lmax[i] = Max = max(A[i], Max); for (int i = n - 1, Max = -1; i >= 0; i--) rmax[i] = Max = max(A[i], Max); int ans = 0; for (int i = 0; i < n; i++) ans += min(lmax[i], rmax[i]) - A[i]; delete []lmax; delete []rmax; return ans; } };后来看到了常数空间复杂度的办法,思路是一样的:
class Solution { public: int trap(int A[], int n) { int a=0; int b=n-1; int Max=0; int leftmax=0; int rightmax=0; while(a<=b){ leftmax=max(leftmax,A[a]); rightmax=max(rightmax,A[b]); if(leftmax<rightmax){ Max+=(leftmax-A[a]); a++; } else{ Max+=(rightmax-A[b]); b--; } } return Max; } };
相关文章推荐
- [Leetcode] Trapping Rain Water (Java)
- LeetCode-407-Trapping Rain Water II(C语言实现)
- [LeetCode][Java] Trapping Rain Water
- [leetcode]407. Trapping Rain Water II
- leetcode 【 Trapping Rain Water 】python 实现
- LeetCode: Trapping Rain Water [041]
- [Leetcode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- leetcode42_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
- LeetCode42 Trapping Rain Water
- LeetCode:Trapping Rain Water
- Leetcode刷题记——Trapping Rain Water(捕获雨水)
- Trapping Rain Water leetcode java